题意描述:
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
解题思路:
Alice: 二叉树!
Bob: 咋了,不喜欢二叉树的题目吗?
Alice: 不不不,二叉树多有意思啊,前序遍历,后续遍历,层序遍历,二叉平衡树,二叉搜索树,红黑树,最大堆,最小堆,多好玩啊。( ̄▽ ̄)/
Bob: 啊,这一题单独求最大深度的话,前序,后续,层序都可以的。
Alice: 对,写个递归应该很容易就找到了。可以从根节点往叶节点计数,每往下一层就加一,到叶节点就返回深度,一层一层递归回去,直到根节点。
Bob:父节点的深度等于左子节点和右子节点的深度最大值加一。
Alice: 对,代码里面需要有一个 max
函数。
Bob: 10行以内就能搞定!!
Alice: hhhhhh
代码:
Python 解法一: 递归遍历二叉树。
# 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:
return self.go(root, 0)
def go(self, node: TreeNode, cnt: int) -> int:
if node == None:
return cnt
else:
return max(self.go(node.left, cnt+1), self.go(node.right, cnt+1))
Python 方法二,从叶节点向根节点计数。少了一层函数调用,更快了一点。
# 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:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
C++ 方法二: 还是递归,不过从叶节点向根节点计数。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root){
return 0;
}else{
return this->max(this->maxDepth(root->left), this->maxDepth(root->right)) + 1;
}
}
int max(int a, int b){
if(a > b){
return a;
}else{
return b;
}
}
};
Java 方法二:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}else{
return this.max(this.maxDepth(root.left), this.maxDepth(root.right)) + 1;
}
}
public int max(int a, int b){
if(a > b){
return a;
}else{
return b;
}
}
}
易错点:
一些测试样例:
- 样例 1
[3,null,3,null,3,null,3,null,3,null,3,null,3,null,3,null,null]
最大深度是 8
- 样例 2
[3,null,null]
最大深度是1
总结:
- 二叉树的前序、后续、中序、按层遍历都会写了么 ?
- 昨天的错题补了吗 ?