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

LeetCode: Balanced Binary Tree [110]

时间:2014-06-20 11:02:54      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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.
按照定义,递归求解即可。


【代码】

/**
 * 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;
        
        //获得左子树高度
        int leftHeight=getHeight(root->left);
        if(leftHeight==-1)return -1;
        //获得右子树高度
        int rightHeight=getHeight(root->right);
        if(rightHeight==-1)return -1;
        
        //判断左右子树高度差是否符合要求, 如果符合要求,则返回当前二叉树的高,如果不符合要求,则返回-1
        if(abs(leftHeight-rightHeight)<=1) 
            return max(leftHeight, rightHeight)+1;
        
        return -1;
    }

    bool isBalanced(TreeNode *root) {
        if(root==NULL)return true;
        
        int height=getHeight(root);
        if(height==-1)return false;
        return true;
        
    }
};


LeetCode: Balanced Binary Tree [110],布布扣,bubuko.com

LeetCode: Balanced Binary Tree [110]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/28384131

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