首页 > 其他 > 详细

[LeetCode] Balanced Binary Tree

时间:2015-08-09 22:27:16      阅读:101      评论: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.

 
 思路: 后序遍历二叉树。同时判断以该节点为根的子树是否是平衡树。如果是则返回该子树的高度,如果不是返回-1
相关题目:《剑指offer》面试题39
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (root == NULL) return true;
        
        if (Depth(root) == -1) {
            return false;
        } else {
            return true;
        }
    }
    
    int Depth(TreeNode* root) {
        if (root == NULL) return 0;
        
        int left_depth = Depth(root->left);
        int right_depth = Depth(root->right);
        
        if (left_depth == -1 || right_depth == -1 || abs(left_depth - right_depth) > 1) {
            return -1;
        } else {
            return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
        }
    }
};

 

[LeetCode] Balanced Binary Tree

原文:http://www.cnblogs.com/vincently/p/4716381.html

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