File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments