Leetcode: Balanced Binary Tree

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root == nullptr) return true;
        stack<TreeNode*> sT;
        TreeNode* t = root;
        while(!sT.empty() || t){
            if(t){
                sT.push(t);
                t = t->left;
            }
            else{
                t = sT.top();
                if(abs( h(t->left) - h(t->right) ) > 1 ) return false;
                sT.pop();
                t = t->right;
            }
        }
        return true;
    }
private:
    int h(TreeNode* root){
        if(root == nullptr) return -1;
        return max( h(root->left),h(root->right) ) + 1;
    }
};

非递归版

posted on 2015-09-28 20:38  泉山绿树  阅读(10)  评论(0)    收藏  举报

导航