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

[LeetCode] Balanced Binary Tree

时间:2015-08-09 22:28:53      阅读:199      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!