前置内容——二叉树的数据结构
二叉树的数据结构如下
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
获取二叉树的高度
使用递归方式获取。
public int calDepth(TreeNode root) {
int h = 0;
if (root.left != null) {
h = Math.max(h, calDepth(root.left) + 1);
}
if (root.right != null) {
h = Math.max(h, calDepth(root.right) + 1);
}
return h;
}