Skip to content

Commit ff49e5a

Browse files
authored
Create univalued-binary-tree.cpp
1 parent fea6e44 commit ff49e5a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/univalued-binary-tree.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
bool isUnivalTree(TreeNode* root) {
16+
vector<TreeNode*> s{root};
17+
while (!s.empty()) {
18+
auto node = s.back(); s.pop_back();
19+
if (!node) {
20+
continue;
21+
}
22+
if (node->val != root->val) {
23+
return false;
24+
}
25+
s.emplace_back(node->left);
26+
s.emplace_back(node->right);
27+
}
28+
return true;
29+
}
30+
};
31+
32+
// Time: O(n)
33+
// Space: O(h)
34+
class Solution2 {
35+
public:
36+
bool isUnivalTree(TreeNode* root) {
37+
return (!root->left || (root->left->val == root->val & isUnivalTree(root->left))) &&
38+
(!root->right || (root->right->val == root->val & isUnivalTree(root->right)));
39+
}
40+
};

0 commit comments

Comments
 (0)