lintcode: Balanced Binary Tree

来源:互联网 发布:java修改文件权限 编辑:程序博客网 时间:2024/06/06 04:41

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.

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root: The root of binary tree.     * @return: True if this Binary tree is Balanced, or false.     */    int height(TreeNode *node){        if(node==NULL){            return 0;        }        return max(height(node->left),height(node->right))+1;    }    bool isBalanced(TreeNode *root) {        // write your code here        if(root==NULL){            return true;        }        int diff=height(root->left)-height(root->right);        if(diff>1||diff<-1){            return false;        }        return isBalanced(root->left) && isBalanced(root->right);    }};

参考:
http://www.cnblogs.com/infinityu/archive/2013/05/11/3073411.html
https://haozhou.gitbooks.io/leetcode-java/content/binarytree/binarytree-balanced.html

0 0
原创粉丝点击