码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree

时间:2014-05-02 07:05:08      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   javascript   

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.

题意:实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过1.

解法一:根据题意有一种解法,即直接递归访问整颗树,计算每个节点两棵子树的高度。但效率不高,这代码会递归访问每个结点的整棵子树,也就是说getHeight函数会反复调用计算同一个结点的高度。算法复杂度为O(NlogN);

bubuko.com,布布扣
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getHeight(TreeNode *root) {
        if(root == NULL) return 0;
        return max(getHeight(root->left),getHeight(root->right)) +1 ;
    }
    bool isBalanced(TreeNode *root) {
        if(root == NULL)
            return false;
        int heightDiff = getHeight(root->left) - getHeight(root->right);
        if(abs(heightDiff) > 1) 
            return false;
        else
            return isBalanced(root->left) && isBalanced(root->right);
    }
};    
bubuko.com,布布扣

解法二:根据解法一思路,我们可以删减部分getHeight的调用,仔细查看getHeight函数,你会发现getHeight不仅可以检查高度,还能检查这棵树是否平衡。那么我们发现子树不平衡时直接返回-1不就可以了嘛。

改进后的算法会从根结点递归检测每棵子树的高度。通过checkHeight方法,以递归方式获取每个结点左右子树的高度,若子树平衡,则返回该子树的实际高度。若子树不平衡,则返回-1。代码复杂度:O(N)时间和O(H)的空间,其中H为树的高度。

bubuko.com,布布扣
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int checkHeight(TreeNode *root) {
        if(root == NULL) return 0;
        
        int leftHeight = checkHeight(root->left);
        if(leftHeight == -1) return -1;
        
        int rightHeight = checkHeight(root->right);
        if(rightHeight == -1) return -1;
        
        int heightDiff = leftHeight - rightHeight;
        if(abs(heightDiff) > 1) return -1;
        else return max(leftHeight,rightHeight)+1;
    }
    bool isBalanced(TreeNode *root) {
        if(checkHeight(root) == -1)
            return false;
        else
            return true;
    }
};
bubuko.com,布布扣

 

Balanced Binary Tree,布布扣,bubuko.com

Balanced Binary Tree

标签:style   blog   class   code   java   javascript   

原文地址:http://www.cnblogs.com/chenbjin/p/3703569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!