二叉树遍历搜索
- Basic Knowing
- EASY
- 94. Binary Tree Inorder Traversal -->前序遍历
- 100. Same Tree -->BFS/DFS
- 101. Symmetric Tree-->BFS/DFS
- 104. Maximum Depth of Binary Tree-->BFS/DFS
- 108. Convert Sorted Array to Binary Search Tree-Recursion
- 110. Balanced Binary Tree ->Recursion
- 111. Minimum Depth of Binary Tree -> BFS
- 872. Leaf-Similar Trees ->DFS
Basic Knowing
Depth-First search(DFS): 深度优先搜索:
---- Inorder traversal: 前序遍历: 左➡️中➡️右 :例及代码见94.
---- Preorder traversal: 中序遍历: 中➡️左➡️右
---- Postorder traversal: 后序遍历: 右➡️中➡️左
Breath-First Search (BFS): 广度优先搜索:层序遍历
DFS基本思想:遍历过程中用栈或队列储存其他子树,之后回溯遍历。
通常两种方法:迭代Iterative 和回溯 recursive
Recursive:
#Easy to read but runtime exceeded
def preorder(root):
return [root.val] + preorder(root.left) + preorder(root.right) if root else []
def inorder(root):
return inorder(root.left) + [root.val] + inorder(root.right) if root else []
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root else []
EASY
94. Binary Tree Inorder Traversal -->前序遍历
iterative:
stack = []
ans = []
while root or stack: #推出循环条件:stack和root都为空
while root: #不为空:遍历到左节点结尾
stack.append(root) #存储节点
root = root.left #找左节点
root = stack.pop() #root 为空:从栈中弹出,输出,遍历右节点
ans.append(root.val)#输出
root = root.right #遍历右节点
return ans
recursive:
res = []
self.helper(root, res)
return res
def helper(self, root, res):
if root:
self.helper(root.left, res)
res.append(root.val)
self.helper(root.right, res)
100. Same Tree -->BFS/DFS
遍历➕配对比较
⚠️ 以下边缘样例:p[]q[],p[1]q[],p[]q[1]
⚠️list括号匹配
iterative BFS:
stack = [(p,q)]
while len(stack):
pnode,qnode = stack.pop()
if pnode==None and qnode==None:#解决边缘样例
pass
elif pnode==None or qnode==None:
return False
else:
if pnode.val != qnode.val:
return False
else:
stack.append((pnode.left,qnode.left))#加两层括号
stack.append((pnode.right,qnode.right))
return True
recursion DFS:
if p==None and q==None:
return True
elif p==None or q==None:
return False
else:
return p.val ==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
101. Symmetric Tree–>BFS/DFS
和100.基本类似。对称:节点匹配左右颠倒
recursive DFS:
p =root.left
q = root.right
return self.helper(p,q)
def helper(self,pnode,qnode):
if not pnode and not qnode:
return True
elif not qnode or not pnode:
return False
else:
return pnode.val == qnode.val and self.helper(pnode.left,qnode.right) and self.helper(pnode.right,qnode.left)
iterative:
stack =[(root.left,root.right)]
while stack:
p,q = stack.pop()
if not p and not q:
pass
elif not p or not q:
return False
else:
if p.val!=q.val: return False
stack.append((p.left,q.right))
stack.append((p.right,q.left))
return True
104. Maximum Depth of Binary Tree–>BFS/DFS
recursive:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
iterative: 每个root后附加层数
if not root:
return 0
maxdep =1
dep = 1
stack = [(root,dep)]
while stack:
root,dep = stack.pop()
if root:
if root.left:
stack.append((root.left,dep+1))
if root.right:
stack.append((root.right,dep+1))
if dep>maxdep: maxdep =dep
return maxdep
108. Convert Sorted Array to Binary Search Tree-Recursion
数组转换为平衡树
if not nums: return None
depth = len(nums)//2 #找到中间点
head = TreeNode(nums[depth])
head.left = self.sortedArrayToBST(nums[:depth])
head.right = self.sortedArrayToBST(nums[depth+1:])
return head
110. Balanced Binary Tree ->Recursion
是否是平衡树
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root: return True
l = self.length(root.left)
r = self.length(root.right)
return abs(l-r)<2 and self.isBalanced(root.left) and self.isBalanced(root.right)
def length(self,node):#输出深度
if node ==None :
return 0
return max(self.length(node.left),self.length(node.right))+1
111. Minimum Depth of Binary Tree -> BFS
树最小长度:找到节点左右为空的深度
和节点一起保存深度
if not root: return 0
queue = [(root, 1)]
while queue:
node, level = queue.pop(0)
if node:
if not node.left and not node.right:
return level
else:
queue.append((node.left, level+1))
queue.append((node.right, level+1))
872. Leaf-Similar Trees ->DFS
比较两树的子节点值是否相同
法:分别遍历两个树,得到两个树子节点的遍历结果做比较。
def dfs(root)->list:
stack=[]
mylist =[]
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if not root.left and not root.right:
mylist.append(root.val)
root = root.right
return mylist
return dfs(root1) == dfs(root2)