关键点 递归的使用
public class TreeHeight {
public static int getTreeHeight(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(getTreeHeight(root.left), getTreeHeight(root.right));//这里直接使用Math.max()函数
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
System.out.println(getTreeHeight(node1));
}
}
class TreeNode {
TreeNode left = null;
TreeNode right = null;
int val;
TreeNode(int val) {
this.val = val;
}
}