1.求二叉树的最大深度
题目:给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节 点数。
二叉树的最大深度为左右子树的最大深度+1
首先使用递归方法求解。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:# 递归到空树时停止
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 #调用自身
在使用递归的时候要注意三点:
1.递归结束的条件是什么
2.什么时候调用自身
3.如何调用自身
本题还可以使用迭代(栈)解决问题
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(1, root)]
depth = 0
while stack:
cur_depth, root = stack.pop()
depth = max(cur_depth, depth)
if root.right:
stack.append((cur_depth+1, root.right))
if root.left:
stack.append((cur_depth+1, root.left))
return depth
因为是先序遍历,所以右孩子先入栈,然后再是左孩子。
在迭代的过程中不断更新depth
最后就得到二叉树的最大深度