按遍历顺序打印节点值和它的下标
前序遍历
def preorder(root):
stack = [root]
index = -1
while stack:
finish = stack.pop()
if finish:
index += 1
print(index, finish.val)
stack.append(finish.right)
stack.append(finish.left)
# 使用列表,调用的函数也可以改变这个列表
def preorderRec(root, index=[-1]):
if not root:
return
index[0] += 1
# print默认end="\n"
print(index[0], root.val, end=",")
preorderRec(root.left, index)
preorderRec(root.right, index)
打印效果
中序遍历
def inorder(root):
stack = []
index = -1
while root or stack:
while root:
stack.append(root)
root = root.left
finish = stack.pop()
index += 1
print(index, finish.val)
root = finish.right
def inorderRec(root, index=[-1]):
if not root:
return
inorderRec(root.left, index)
index[0] += 1
print(index[0], root.val)
inorderRec(root.right, index)
后序遍历
def postorder(root):
stack = []
index = -1
while root or stack:
while root:
stack.append(root)
if root.left:
root = root.left
else:
root = root.right
finish = stack.pop()
index += 1
print(index, finish.val)
if stack and finish == stack[-1].left:
root = stack[-1].right
def postorderRec(root, index=[-1]):
if not root:
return
postorderRec(root.left, index)
postorderRec(root.right, index)
index[0] += 1
print(index[0], root.val)
层序遍历 BFS 广度优先遍历
打印每层的宽度,节点值
def levelorder2(root):
ans = []
if not root:
return ans
queue = deque()
queue.append(root)
while queue:
n = len(queue)
s = ""
for i in range(n):
finish = queue.popleft()
print(finish.val,end=",")
s += finish.val
if finish.left:
queue.append(finish.left)
if finish.right:
queue.append(finish.right)
ans.append((n,s))
print()
return ans
打印效果
深度遍历 DFS 深度优先遍历
打印每个路径和它的深度
# 树所有分支的高度和路径,容易求得最大/小高度,最长/近路径
def depthAndPath(root):
if not root:
return []
ans = [(1,root.val)]
childs = depthAndPath(root.left) + depthAndPath(root.right)
if childs:
ans = [(depth+1, root.val+path) for depth,path in childs]
return ans
打印效果
树的最大高度,最小高度可以看作是上面通用深度遍历的特殊情形
# 树的最大高度
def maxDepth(root):
if not root:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
# 树的最小高度
def minDepth(root):
if not root:
return 0
# 如果有节点是空,那么最小高度就是不为空的那个节点,即空节点和另一个节点间大的作为子树最小高度(当两个节点都为空时,最大值是0)
if not root.left or not root.right:
return 1 + max(minDepth(root.left), minDepth(root.right))
# 两个节点非空再选择最小的节点高度加1
return 1 + min(minDepth(root.left), minDepth(root.right))
```