zoukankan      html  css  js  c++  java
  • LeetCode(110) Balanced Binary Tree

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        int indicator = 1;
    public:
        int maxDepth(TreeNode* root) {
    
            if(root == NULL)
                return 0;
    
            int leftDepth = maxDepth(root->left);
            int rightDepth = maxDepth(root->right);
            if(leftDepth > rightDepth )
                return leftDepth + 1;
            else
                return rightDepth + 1;
        }
        void check(TreeNode *root) {
    
            if(root == NULL)
                return;
    
             if(indicator == 0)
                return;
    
            int heightDiffer = maxDepth(root->left) - maxDepth(root->right);
            if(heightDiffer >1 || heightDiffer < -1) {
                indicator = 0;
                return;
            }
            check(root->left);
            check(root->right);
        }
        bool isBalanced(TreeNode* root) {
            check(root);
            if(indicator == 0)
                return false;
            else 
                return true;
        }
    };

    经过一段时间的训练。发现上面的做法会多次遍历同一节点。受到剑指offer P209面试题39题目二解法的启示重写例如以下。执行时间只为曾经的一半8ms(这一次换成了c语言。由于大多数嵌入式公司要求的是c)

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    bool isBalancedInner(struct TreeNode* root, int* height);
    bool isBalanced(struct TreeNode* root)
    {
        int height;
        return isBalancedInner(root, &height);
    }
    bool isBalancedInner(struct TreeNode* root, int* height)
    {
        if(!root)
        {
            *height = 0;
            return true;
        }
    
        int leftHeight, rightHeight;
        bool leftIsBalanced = isBalancedInner(root->left, &leftHeight);
        bool rightIsBalanced = isBalancedInner(root->right, &rightHeight);
    
        if(!leftIsBalanced || !rightIsBalanced)
            return false;
        else
        {
            *height = leftHeight > rightHeight ? (leftHeight + 1) : (rightHeight + 1);
            return (leftHeight - rightHeight > 1) || (leftHeight - rightHeight < -1) ? false : true;
        }
    
    }
  • 相关阅读:
    hdu 5534(dp)
    hdu 5533(几何水)
    hdu 5532(最长上升子序列)
    *hdu 5536(字典树的运用)
    hdu 5538(水)
    假如数组接收到一个null,那么应该怎么循环输出。百度结果,都需要提前判断。否则出现空指针异常。。我还是想在数组中实现保存和输出null。
    第一个登录页面 碰到的疑问
    浅谈堆和栈的区别
    Java中的基础----堆与栈的介绍、区别
    JS的Document属性和方法
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7246122.html
Copyright © 2011-2022 走看看