-
Notifications
You must be signed in to change notification settings - Fork 0
/
Build-BinTree-from-PreInorderTraversal.py
71 lines (50 loc) · 2.06 KB
/
Build-BinTree-from-PreInorderTraversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(inorder) < 1:
return None
root = TreeNode(preorder[0])
rootindex = inorder.index(root.val)
lefttree = inorder[:rootindex]
righttree = inorder[rootindex+1:]
preorder.remove(root.val)
root.left = self.buildTree(preorder,lefttree)
root.right = self.buildTree(preorder, righttree)
return root
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
def buildTree(r1,r2):
nxtNode = TreeNode()
if not r1 and not r2:
return
if r1 and r2:
nxtNode = TreeNode(r1.val + r2.val)
else:
if not r1 and r2:
nxtNode = TreeNode(r2.val)
elif r1 and not r2:
nxtNode = TreeNode(r1.val)
else:
nxtNode = TreeNode(r1.val or r2.val)
if r1.left and r2.left:
nxtNode.left = buildTree(r1.left,r2.left)
else:
nxtNode.left = r1.left or r2.left
if r1.right and r2.right:
nxtNode.right = buildTree(r1.right, r2.right)
else:
nxtNode.right = r1.right or r2.right
return nxtNode
if not root1:
return root2
if not root2:
return root1
rtnode = TreeNode(root1.val + root2.val)
print(rtnode)
rtnode.left = buildTree(root1.left, root2.left)
rtnode.right = buildTree(root1.right, root2.right)
return rtnode