Skip to content

Commit fea6e44

Browse files
authored
Create univalued-binary-tree.py
1 parent 432f9da commit fea6e44

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Diff for: Python/univalued-binary-tree.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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)))

0 commit comments

Comments
 (0)