二叉树的深度相关问题

来源:互联网 发布:工作便签软件 编辑:程序博客网 时间:2024/05/23 14:23

题目

输入一颗二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的结点形成树的一条路径,最长路径的长度为树的深度。

思路

简化一下题目,思考一个节点的时候二叉树的深度为 1,因为左右子树都为0;
2个节点的时候二叉树深度为 2,左右子树的深度最大值加 1;
3个节点分两种情况:
   4                   3
  /  \                    \
3   5                   4
                             \
                             5
我们由这两种情况可以看出来,任意一颗二叉树的深度就是它的左右子树的深度最大值加 1
第一种:因为3,5的深度都为1,所以4的深度为2
第二种:5的深度为1,4的深度为2,3的深度即为3
.....

代码如下

public static int getDeep(BinaryTree root ){if(root==null){return 0;}int nleft = getDeep(root.left);int nright = getDeep(root.right);return  nleft > nright ? nleft+1 : nright +1;}


延伸

如何判断一棵二叉树为平衡二叉树(任意节点的左右子树的深度相差不超过1)。

我们可以借用上面的思想,代码实现如下:

public static boolean isBalanced(BinaryTree root) {                if(root == null)return true;        int in = getDeep1(root);        if(in >= 0)            return true;        else            return false;            }        public static int getDeep(BinaryTree root ){if(root==null){return 0;}int nleft = getDeep(root.left);int nright = getDeep(root.right);//System.out.println("root:"+root.value);   可以将中间结果打印出来看详细过程//System.out.println("left:"+nleft);//System.out.println("right:"+nright);                if(nright <0 || nleft < 0) return -1;    //如果小于0,就说明上一步的左右子树相差必然超过1了,所以直接返回                if(Math.abs(nleft-nright) >1)return -1;   //左右子树相差超过1,返回-1        return  nleft > nright ? nleft+1 : nright +1;   //返回二叉树的深度}


0 0