Balanced Binary Tree

来源:互联网 发布:MAC 百度网盘 编辑:程序博客网 时间:2024/05/16 05:06

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 ofevery node never differ by more than 1.

用递归来解,对于每一层检验是否为平衡的,如果当前某个子树不平衡,则直接返回不平衡,否则返回当前的深度值,用-1来标记不平衡。

class Solution {public:    bool isBalanced(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function             return (cal_depth(root) >= 0)?true:false;            }        int cal_depth(TreeNode *root)    {        if(root == NULL) return 0;                int left_depth = cal_depth(root->left) ;        if(left_depth < 0) return -1;                int right_depth = cal_depth(root->right);        if(right_depth < 0) return -1;                if(abs(left_depth - right_depth) > 1) return -1;                 return 1+max(left_depth,right_depth);    }};
64 milli secs




原创粉丝点击