时间:2020-5-15
题目地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
题目难度:Easy
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
思路1:递归,自底向上,dfs
代码段1:通过
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
else:
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1
总结:
- 一开始想的是使用2^n-1索引位置确定层级,这样太复杂了,后边就换成递归了
- 递归还是写的少
思路2:递归,自顶向下【2020-8-3】
代码段2:通过
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def top_down(node, depth):
if node is None: return depth
else:
return max(top_down(node.left, depth + 1), top_down(node.right, depth + 1))
return top_down(root, 0)
总结:
-
“自顶向下”和“自底向上”的最终定义:
在树的递归算法中,“自顶向下”指的是通过给函数传参的方式让信息流从根结点向下走,从而求得最终结果的过程。
在树的递归算法中,“自底向上”指的是通过函数返回值让信息流从叶结点向上走,从而求得最终结果的过程。
思路3:使用队列,使用特殊元素区分每一层,树的层序遍历,bfs
代码段3:通过
from collections import deque
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
q, result = [root, None], 1
while q:
temp = q.pop(0)
if (temp):
if(temp.left):q.append(temp.left)
if(temp.right):q.append(temp.right)
elif q:
q.append(None)
result += 1
return result
总结:
- 层序遍历使用这种方式好使