/*
* 面试题55-题目一:二叉树的深度
* 题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
* 思路:树的深度就是:左右子树的较大值加1.
*/
class TreeNode6 {
int val = 0;
TreeNode6 left = null;
TreeNode6 right = null;
public TreeNode6(int val) {
this.val = val;
}
}
public class No55TreeDepth {
public static void main(String[] args) {
No55TreeDepth n = new No55TreeDepth();
TreeNode6 root = new TreeNode6(1);
TreeNode6 p2 = new TreeNode6(2);
TreeNode6 p3 = new TreeNode6(3);
TreeNode6 p4 = new TreeNode6(4);
TreeNode6 p5 = new TreeNode6(5);
TreeNode6 p6 = new TreeNode6(6);
TreeNode6 p7 = new TreeNode6(7);
root.left = p2;
root.right = p3;
p2.left = p4;
p2.right = p5;
p5.left = p7;
p3.right = p6;
System.out.println(n.TreeDepth(root));
}
public int TreeDepth(TreeNode6 root) {
if (root == null) {
return 0;
}
//求左右子树的深度
int nLeft = TreeDepth(root.left);
int nRight = TreeDepth(root.right);
//返回大值加1即为树的深度
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
}
面试题55-题目一:二叉树的深度
最新推荐文章于 2022-01-24 18:58:37 发布