-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunivalued_binary_tree.cpp
More file actions
27 lines (23 loc) 路 902 Bytes
/
Copy pathunivalued_binary_tree.cpp
File metadata and controls
27 lines (23 loc) 路 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// https://leetcode.com/problems/univalued-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
return isUnivalTreeHelper(root, root->val);
}
bool isUnivalTreeHelper(TreeNode* root, int& orig_val) {
if (root == NULL) return true;
if (root->left == NULL && root->right == NULL) return (root->val == orig_val) ? true : false;
return (root->val != orig_val) ? false : ( isUnivalTreeHelper(root->left, orig_val) && isUnivalTreeHelper(root->right, orig_val) );
}
};