File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(n)
2
+ # Space: O(h)
3
+
4
+ # Definition for a binary tree node.
5
+ class TreeNode (object ):
6
+ def __init__ (self , x ):
7
+ self .val = x
8
+ self .left = None
9
+ self .right = None
10
+
11
+
12
+ class Solution (object ):
13
+ def isUnivalTree (self , root ):
14
+ """
15
+ :type root: TreeNode
16
+ :rtype: bool
17
+ """
18
+ s = [root ]
19
+ while s :
20
+ node = s .pop ()
21
+ if not node :
22
+ continue
23
+ if node .val != root .val :
24
+ return False
25
+ s .append (node .left )
26
+ s .append (node .right )
27
+ return True
28
+
29
+
30
+ # Time: O(n)
31
+ # Space: O(h)
32
+ class Solution2 (object ):
33
+ def isUnivalTree (self , root ):
34
+ """
35
+ :type root: TreeNode
36
+ :rtype: bool
37
+ """
38
+ return (not root .left or (root .left .val == root .val and self .isUnivalTree (root .left ))) and \
39
+ (not root .right or (root .right .val == root .val and self .isUnivalTree (root .right )))
You can’t perform that action at this time.
0 commit comments