首页 > 其他 > 详细

leetcode[110] Balanced Binary Tree

时间:2014-11-30 00:22:19      阅读:295      评论:0      收藏:0      [点我收藏+]

判断一棵树是不是平衡二叉树。

思路:递归。

每个节点的左右子树是平衡二叉树,并且左右子树的高度相差不超过一。

/**
 * 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 heightTree(TreeNode *root)
    {
        if (!root) return 0;
        int lf = 0, ri = 0;
        if (root -> left)
            lf = heightTree(root -> left);
        if (root -> right)
            ri = heightTree(root -> right);
        return max(lf, ri) + 1;
    }
    
    bool isBalanced(TreeNode *root) {
        if (!root) return true;
        bool lf, ri;
        lf = isBalanced(root -> left);
        ri = isBalanced(root -> right);
        return lf && ri && (abs(heightTree(root->left)-heightTree(root->right))<=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 heightTree(TreeNode *root)
    {
        if (!root) return 0;
        int lf = 0, ri = 0;
        if (root -> left)
            lf = heightTree(root -> left);
        if (root -> right)
            ri = heightTree(root -> right);
        return max(lf, ri) + 1;
    }
    
    bool isBalanced(TreeNode *root) {
        if (!root) return true;
        
        stack<TreeNode *> sta;
        TreeNode *p = root;
        
        while(p || !sta.empty())
        {
            while(p)
            {
                sta.push(p);
                p = p -> left;
            }
            if (!sta.empty())
            {
                p = sta.top();
                sta.pop();
                if (abs(heightTree(p -> left) - heightTree(p -> right)) > 1)
                    return false;
                p = p -> right;
            }
        }
        return true;
    }
};

 

leetcode[110] Balanced Binary Tree

原文:http://www.cnblogs.com/higerzhang/p/4132243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!