您的位置:首页 > 编程语言

leetcode:110 Balanced Binary Tree-每日编程第十九题

2015-12-11 10:46 507 查看
Balanced Binary Tree

Total
Accepted: 85721 Total
Submissions: 261445 Difficulty: Easy

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).判断root是否平衡(即左右子树的高是否相差在1 内),平衡转2).,如果不平衡,则返回false;

2).判断root的左子树是否平衡,root的右子树是否平衡,即把root的左右节点当成root并重复1).

3).直到NULL结束。

/**
 * 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:
    int getHeight(TreeNode* root){
        if(root==NULL){
            return 0;
        }else{
            return max(getHeight(root->left),getHeight(root->right))+1;
        }
    }

    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        int m = getHeight(root->left);
        int n = getHeight(root->right);
        if(abs(n-m)<=1){
            return isBalanced(root->left)&&isBalanced(root->right);
        }else{
            return false;
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: