- 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int hight = 0;
int count = 0;
public int maxDepth(TreeNode root) {
dfs(root);
return hight;
}
public void dfs(TreeNode curNode){
count++;
if(curNode == null){
return;
}
if(curNode.left == null && curNode.right == null){
hight = Math.max(hight,count);
return;
}
dfs(curNode.left);
count--;
dfs(curNode.right);
count--;
return;
}
}
class Solution2 {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
笔记
- 我的解法实际上是在求最远路径的长度,如果把count改成数组也可以求最远路径。
- Solution2 是标准解法,对于树也许可以从下往上考虑,就是先考虑几个点的情况,然后往上加,这样有助于思考递归的结束位置。或者开始位置?