利用递归求二叉树的深度,原理是给出一棵二叉数Tree,要求它的深度height,就要求它的左子树leftTree与右子树rightTree的深度,取深度较大的一方,那么这棵二叉树的深度为height = Max(leftHeight,rightHeight) + 1(Max是取值大的一方),那么要求左子树与右子树的深度(原理同上),依次类推即可求出二叉树的深度。
public int height(TreeNode root) {
//如果根节点为空,直接返回树的深度为0
if(root == null){
return 0;
}
TreeNode node = root;
int leftHeight = 0;
int rightHeight = 0;
if (node!=null) {
//利用递归,分别求左子树与右子树的深度
leftHeight = height(node.left) + 1;
rightHeight = height(node.right) + 1;
}
//取两深度的较大值
return leftHeight>rightHeight?leftHeight:rightHeight;
}