现在的位置: 首页 > 综合 > 正文

Balanced Binary Tree

2014年01月28日 ⁄ 综合 ⁄ 共 720字 ⁄ 字号 评论关闭

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.

一次AC

平衡二叉树, 左右子树都是, 且深度差在1之内

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int depthTree(TreeNode *root)
    {
        if(!root)
            return 0;
        if(!root->left&&!root->right)
            return 1;
        else 
            return 1 + max(depthTree(root->left), depthTree(root->right));
    }
    bool isBalanced(TreeNode *root) {
        if(!root)
            return true;
        int diff_depth = depthTree(root->left) - depthTree(root->right);
        if(isBalanced(root->left)&&isBalanced(root->right)&&diff_depth>=-1&&diff_depth<=1)
            return true;
        return false;
    }
};

抱歉!评论已关闭.