Skip to content

Commit 267bbb5

Browse files
authored
Create flip-binary-tree-to-match-preorder-traversal.py
1 parent 9faf1f2 commit 267bbb5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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 flipMatchVoyage(self, root, voyage):
14+
"""
15+
:type root: TreeNode
16+
:type voyage: List[int]
17+
:rtype: List[int]
18+
"""
19+
def dfs(root, voyage, i, result):
20+
if not root:
21+
return True
22+
if root.val != voyage[i[0]]:
23+
return False
24+
i[0] += 1
25+
if root.left and root.left.val != voyage[i[0]]:
26+
result.append(root.val)
27+
return dfs(root.right, voyage, i, result) and \
28+
dfs(root.left, voyage, i, result)
29+
return dfs(root.left, voyage, i, result) and \
30+
dfs(root.right, voyage, i, result)
31+
32+
result = []
33+
return result if dfs(root, voyage, [0], result) else [-1]

0 commit comments

Comments
 (0)