版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014204761/article/details/82935790
def levelOrder(self, root):
"""
和普通的层次遍历不一样的地方是输出结果是每层一个列表的形式
"""
if not root:
return []
res = []
arr = []
stack = [root] ####存放每一层的子节点
tmp = []
while stack:
while stack:
root = stack.pop(0)
arr.append(root.val)
if root.left:
tmp.append(root.left)
if root.right:
tmp.append(root.right)
res.append(arr)
arr = []
stack = tmp
tmp = []
return res
leetcode107 二叉树的层次遍历II只需要把结果逆序即可。return res[::-1]
leetcode 104 二叉树的最大深度
def maxDepth(self, root):
"""
最大深度也是层次遍历
"""
if not root:
return 0
count = 0
arr = []
stack = [root] ####存放每一层的子节点
tmp = []
while stack:
while stack:
root = stack.pop(0)
arr.append(root.val)
if root.left:
tmp.append(root.left)
if root.right:
tmp.append(root.right)
count += 1
arr = []
stack = tmp
tmp = []
return count
leetcode 111 二叉树的最小深度
def minDepth(self, root):
"""
最小深度在层次遍历上加个判定条件即可
"""
if not root:
return 0
count = 0
arr = []
stack = [root] ####存放每一层的子节点
tmp = []
while stack:
while stack:
root = stack.pop(0)
arr.append(root.val)
if root.left:
tmp.append(root.left)
if root.right:
tmp.append(root.right)
###如果出现叶子节点 返回
if not root.left and not root.right:
count += 1
return count
count += 1
arr = []
stack = tmp
tmp = []
return count