array
to represent the
complete binary tree
,and
store the root node at index 1
parent
node of any node is
[index of the node / 2]
left child
node is
[index of the node * 2]
right child
node is
[index of the node * 2 + 1]
n is "index"
Let’s say you have a complete binary tree like this:
10
/ \
15 20
/ \ /
30 40 50
This tree as an array (1-based) would be:
Index: 1 2 3 4 5 6
Value: [10, 15, 20, 30, 40, 50]
Relationships:
Node at index 2 (15)
Complete binary tree
except possibly the last
, is completely filled, and all
nodes in the last level are as far left as possible.
Types
Algorithm
Data structure
LC 105
https://github.com/yennanliu/CS_basics/blob/master/leetcode_python/Recursion/construct-binary-tree-from-preorder-and-inorder-traversal.py
NOTE !!!
symmetric
, so the
distance(left-sub-tree, root), distance(right-sub-tree, root) is the
sameroot
always at first element when PreorderSteps
Preorder :
root ---- left ---- right
<--> <-->
idx idx
Inorder :
left ---- root ---- right
<--> <-->
idx idx
so we can use below go represent left, right sub tree in Preorder and Inorder
# python
# Preorder:
# left sub tree : preorder[1 : index + 1]
# right sub tree : preorder[index + 1 : ]
# Inorder
# left sub tree : inorder[ : index]
# right sub tree : inorder[index + 1 :]
# python
# LC 105. Construct Binary Tree from Preorder and Inorder Traversal
# V0
# IDEA : BST property
class Solution(object):
def buildTree(self, preorder, inorder):
if len(preorder) == 0:
return None
if len(preorder) == 1:
return TreeNode(preorder[0])
### NOTE : init root like below (via TreeNode and root value (preorder[0]))
= TreeNode(preorder[0])
root """
NOTE !!!
-> # we get index of root.val from "INORDER" to SPLIT TREE
"""
= inorder.index(root.val) # the index of root at inorder, and we can also get the length of left-sub-tree, right-sub-tree ( preorder[1:index+1]) for following using
index # recursion for root.left
#### NOTE : the idx is from "INORDER"
#### NOTE : WE idx from inorder in preorder as well
#### NOTE : preorder[1 : index + 1] (for left sub tree)
= self.buildTree(preorder[1 : index + 1], inorder[ : index]) ### since the BST is symmery so the length of left-sub-tree is same in both Preorder and Inorder, so we can use the index to get the left-sub-tree of Preorder as well
root.left # recursion for root.right
= self.buildTree(preorder[index + 1 : ], inorder[index + 1 :]) ### since the BST is symmery so the length of left-sub-tree is same in both Preorder and Inorder, so we can use the index to get the right-sub-tree of Preorder as well
root.right return root
# python
# LC 106 Construct Binary Tree from Inorder and Postorder Traversal
# V0
# IDEA : Binary Tree property, same as LC 105
class Solution(object):
def buildTree(self, inorder, postorder):
if not inorder:
return None
if len(inorder) == 1:
return TreeNode(inorder[0])
### NOTE : we get root from postorder
= TreeNode(postorder[-1])
root """
### NOTE : the index is from inorder
### NOTE : we get index of root in inorder
# -> and this idx CAN BE USED IN BOTH inorder, postorder (Binary Tree property)
"""
= inorder.index(root.val)
idx ### NOTE : inorder[:idx], postorder[:idx]
= self.buildTree(inorder[:idx], postorder[:idx])
root.left ### NOTE : postorder[idx:-1]
= self.buildTree(inorder[idx+1:], postorder[idx:-1])
root.right return root
# LC 257 Binary Tree Paths
# V0
# IDEA : BFS
class Solution:
def binaryTreePaths(self, root):
= []
res ### NOTE : we set q like this : [[root, cur]]
= ""
cur = [[root, cur]]
q while q:
for i in range(len(q)):
= q.pop(0)
node, cur ### NOTE : if node exist, but no sub tree (i.e. not root.left and not root.right)
# -> append cur to result
if node:
if not node.left and not node.right:
+ str(node.val))
res.append(cur ### NOTE : we keep cur to left sub tree
if node.left:
+ str(node.val) + '->'))
q.append((node.left, cur ### NOTE : we keep cur to left sub tree
if node.right:
+ str(node.val) + '->'))
q.append((node.right, cur return res
# V0'
# IDEA : DFS
class Solution:
def binaryTreePaths(self, root):
= []
ans def dfs(r, tmp):
if r.left:
+ [str(r.left.val)])
dfs(r.left, tmp if r.right:
+ [str(r.right.val)])
dfs(r.right, tmp if not r.left and not r.right:
'->'.join(tmp))
ans.append(if not root:
return []
str(root.val)])
dfs(root, [return ans
# LC 298 Binary Tree Longest Consecutive Sequence
# V0
# IDEA : DFS
class Solution(object):
def longestConsecutive(self, root):
if not root:
return 0
self.result = 0
self.helper(root, 1)
return self.result
def helper(self, root, curLen):
self.result = curLen if curLen > self.result else self.result
if root.left:
if root.left.val == root.val + 1:
self.helper(root.left, curLen + 1)
else:
self.helper(root.left, 1)
if root.right:
if root.right.val == root.val + 1:
self.helper(root.right, curLen + 1)
else:
self.helper(root.right, 1)
# V0'
# IDEA : BFS
class Solution(object):
def longestConsecutive(self, root):
if root is None:
return 0
= list()
stack 1))
stack.append((root, = 1
maxLen while len(stack) > 0:
= stack.pop()
node, pathLen if node.left is not None:
if node.val + 1 == node.left.val:
+ 1))
stack.append((node.left, pathLen = max(maxLen, pathLen + 1)
maxLen else:
1))
stack.append((node.left, if node.right is not None:
if node.val + 1 == node.right.val:
+ 1))
stack.append((node.right, pathLen = max(maxLen, pathLen + 1)
maxLen else:
1))
stack.append((node.right,
return maxLen
# LC 173. Binary Search Tree Iterator
# V0
# IDEA : STACK + tree
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.inOrder(root)
def inOrder(self, root):
if not root:
return
self.inOrder(root.right)
self.stack.append(root.val)
self.inOrder(root.left)
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0
def next(self):
"""
:rtype: int
"""
return self.stack.pop()