Balanced Binary Tree

使用辅助函数height(root),如果以root为根的树是balanced,则返回该树的高度,否则返回-1。代码如下:

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        return height(root) >= 0;
    }
    
    //if the root is not a balance tree, return -1;
    //otherwise return the height or the tree.
    int height(TreeNode *root)
    {
        if(root == NULL) return 0;
        
        int left = height(root->left);
        int right= height(root->right);
        
        if(left==-1 || right==-1 || abs(left-right)>1) return -1;
        
        return max(left, right)+1;
    }
};

非递归写法。

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if(root == NULL) return true;
        unordered_map<TreeNode*, int> map;
        stack<pair<TreeNode*,int> > stack;
        
        stack.push(make_pair(root, 0));
        while(!stack.empty())
        {
            TreeNode *cur = stack.top().first;
            int status = stack.top().second;
            
            if(status < 2)
            {
                stack.top().second++;
                if(status == 0 && cur->left)
                {
                    stack.push(make_pair(cur->left, 0));
                }
                if(status == 1 && cur->right)
                {
                    stack.push(make_pair(cur->right, 0));
                }
            }
            else
            {
                int left_height = cur->left? map[cur->left]:0;
                int right_height= cur->right? map[cur->right]:0;
                
                if(abs(left_height-right_height) > 1) return false;
                map[cur] = max(left_height, right_height) + 1;
                
                stack.pop();
            }
        }
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值