/**
* 题目:二叉树的深度。 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
*
* @author hexiaoli 思路:剑指offer 思路: 1)递归方法,使用DFS(深度优先搜索)。
*/
class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Main {
public static int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int nodeLeft = TreeDepth(root.left);
int nodeRight = TreeDepth(root.right);
return (nodeLeft > nodeRight) ? nodeLeft + 1 : nodeRight + 1;
}
public static void main(String[] args) {
TreeNode head = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
TreeNode left1 = new TreeNode(4);
TreeNode right1 = new TreeNode(5);
TreeNode left2 = new TreeNode(6);
TreeNode right3 = new TreeNode(7);
head.left = left;
head.right = right;
left.left = left1;
left.right = right1;
right1.left = right3;
right.right = left2;
System.out.println(TreeDepth(head));
}
}