题目内容 二叉树的深度
尝试一
结果:答案正确:恭喜!您提交的程序通过了所有的测试用例
代码:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
/* 特殊情况处理,递归结束标识*/
if(root==null){
return 0;
}
/* 左右子节点递归。这里的代码我合并到下面去了*/
/* 比较大小返回最大值*/
return Math.max(TreeDepth(root.left)+1,TreeDepth(root.right)+1);
}
}
分析:利用递归,先序遍历,然后比较左右子树的深度大小
这道题,我是看了一下讨论的。如果没看的话,比较大小我就不用
Math.max(TreeDepth(root.left)+1,TreeDepth(root.right)+1);
,我会在递归结束标识root==null
时判断(当然就需要一个全局变量来存当前二叉树的最大深度好进行比较,并且TreeDepth还需要一个参数,那就是当前节点的层数-1)。可以参考一下 二叉树中和为某一值的路径,二叉树求深度
总结
- 二叉树深度遍历 可用
Math.max(TreeDepth(root.left)+1,TreeDepth(root.right)+1);
来比较左右子树深度大小。