Skip to content

Commit 0eeaa6a

Browse files
author
kaidi
committed
add 938
1 parent 473f005 commit 0eeaa6a

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

Tree/105. Construct Binary Tree from Preorder and Inorder Traversal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
4040
merely let it pop out the first element in every recursion
4141
so when the code runs to line root.right = self.buildTree(preorder,right_inorder)
4242
what left of preorder list is exactly the same as above right_preorder
43-
but do mind, in this way, we MUST put root.left=self.buildtree() BEFORE root.right=self.buildTree()
43+
but do keep in mind, in this way, we MUST put root.left=self.buildtree() BEFORE root.right=self.buildTree()
4444
'''
4545

4646
class Solution:

Tree/938. Range Sum of BST.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
8+
class Solution:
9+
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
10+
stack = []
11+
s=0
12+
while root or stack:
13+
while root:
14+
stack.append(root)
15+
if root.val > low:
16+
root=root.left
17+
else:
18+
break
19+
root = stack.pop()
20+
if low <= root.val <= high:
21+
s+=root.val
22+
if root.val < high:
23+
root = root.right
24+
else:
25+
root=None
26+
return s
27+
28+
# Since the tree is already sorted,
29+
# we add two if statements to stop the search of sub left/right tree when root.val is out of the boundary

Tree/Tree_all_traversal.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
1+
2+
# [1]
3+
# / \
4+
# [2] [3]
5+
# / \
6+
# [4] [5]
7+
#
8+
#
9+
# Depth First Traversals:
10+
# (a) Inorder (Left, Root, Right) : 4 2 5 1 3
11+
# (b) Preorder (Root, Left, Right) : 1 2 4 5 3
12+
# (c) Postorder (Left, Right, Root) : 4 5 2 3 1
13+
# Breadth-First or Level Order Traversal: 1 2 3 4 5
14+
15+
# Definition for a binary tree node.
16+
# class TreeNode:
17+
# def __init__(self, val=0, left=None, right=None):
18+
# self.val = val
19+
# self.left = left
20+
# self.right = right
21+
22+
# We prefer iterative than recursion because recursion algorithms have an overhead for procedure calls
23+
24+
25+
26+
127
# compare two tree is identical
228
def identical(s, t):
329
if s is None and t is None:

0 commit comments

Comments
 (0)