[LeetCode] Balanced Binary Tree

来源:互联网 发布:企业网络架构图 编辑:程序博客网 时间:2024/06/08 02:42

Balanced Binary Tree

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。若大于1,则返回false,否则检查左孩子树和右孩子树是否均是平衡树。

/** * 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;        }        int leftH = TreeHeight(root->left);        int rightH = TreeHeight(root->right);        if(leftH > rightH + 1 || leftH < rightH -1){            return false;        }        return isBalanced(root->left) && isBalanced(root->right);    }        int TreeHeight(TreeNode* root){        if(root==NULL){            return 0;        }else{            return 1+max(TreeHeight(root->left), TreeHeight(root->right));        }    }    };


0 0