首页 > 其他 > 详细

[Leetcode]-Balanced Binary Tree

时间:2015-07-06 12:24:30      阅读:194      评论:0      收藏:0      [点我收藏+]

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.

Hide Tags: Tree ,Depth-first Search
题目:判断一颗二叉树是否为平衡二叉树
思路:此题是Maximum Depth of Binary Tree 题目的延伸题目,递归判断每个节点的左右子树的最大深度是否只相差1。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxDepth(struct TreeNode* root) {
    if(root == NULL)    return 0;
    if(root->left == NULL && root->right == NULL)   return 1;
    else if(root->left == NULL) return maxDepth(root->right) + 1;
    else if(root->right== NULL) return maxDepth(root->left ) + 1;

    int l = maxDepth(root->left) + 1;
    int r = maxDepth(root->right)+ 1;
    return l>r?l:r;
}

bool isBalanced(struct TreeNode* root) {
    if(root == NULL)    
        return true;//递归终止条件
    if (abs(maxDepth(root->left) - maxDepth(root->right)) >1)
        return false;//左右子树最大深度是否相差1
    return isBalanced(root->left) && isBalanced(root->right);//递归查找每个节点的左右子树最大深度
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]-Balanced Binary Tree

原文:http://blog.csdn.net/xiabodan/article/details/46771309

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!