zoukankan      html  css  js  c++  java
  • leetcode[110] Balanced Binary Tree

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

    思路:递归。

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

    /**
     * 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;
        }
    };
  • 相关阅读:
    Global.asax 文件是什么
    C和C++语言学习总结
    iphone窗口传值
    c语言实现队列
    iphone窗口跳转
    NSStirng、NSArray、 文件 以及枚举(Method小集合)
    服务器接受的链接过多,该怎么处理
    c语言实现单链表
    iphone开发 NSXMLParser解析xml文件
    iphone 切换界面
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4132243.html
Copyright © 2011-2022 走看看