题目:输入一棵二叉树的根结点,求该树的深度。从根结点到叶子点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
代码如下:
package demo;
public class Test39_1 {
private static class BinaryTreeNode {
int val;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode() {
}
public BinaryTreeNode(int val) {
this.val = val;
}
}
public static int treeDepth(BinaryTreeNode root) {
if (root == null) {
return 0;
}
int left = treeDepth(root.left);
int right = treeDepth(root.right);
return left > right ? (left + 1) : (right + 1);
}
}