LeetCode-Balanced Binary Tree && 二叉树的深度 && 二叉树的平衡

作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/26359533
时间:2014-5-20

题目



Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

《剑指offer-面试题39》P207
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

二叉树定义如下:

struct BinaryTreeNode
{
  int m_nValue;
  BinaryTreeNode* m_pLeft;
  BinaryTreeNode* m_pRight;
}



题目二:输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

解法

迭代

第一种想法有点像所见即所得。
无非就先算层次深度,然后计算一下左右子树的差别,然后判断输出真假。
就像我们本科时候学过的:
如果左右子树的深度差大于等于2的话,返回不平衡。(1计算深度,2比较,3子树要迭代)


public boolean isBalanced(TreeNode root) {
        if(root==null )
            return true;
        int diff = Depth(root.left)-Depth(root.right);
        if(diff > 1 || diff < -1)
            return false;
        return isBalanced(root.left) && isBalanced(root.right);
        
    }
    
    public int Depth(TreeNode root){
        if(root == null)
            return 0;
        int left = Depth(root.left);
        int right = Depth(root.right);
        return  left>right ? left+1 : right + 1;
    }



另一种想法




public static int depth=0;
    public static int left=0,right=0;
    public static int diff = 0; 
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            depth = 0;
            return true;
        }
        if(isBalanced(root.left,left)&&isBalanced(root.right,right)){
            diff = left - right;
            if(diff<=1 && diff > -1){
                depth = left > right ? left +1 : right + 1;
                return true; 
            }
        }
        return false;
        
    }

返回

LeetCode Solution(持续更新,java>c++)






    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/disappearedgod/article/details/26359533
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞