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;
        }
    
    }
  • 相关阅读:
    okhttp连接池:put,get方法&connection回收
    okhttp拦截器之ConnectInterceptor解析
    okhttp拦截器之CacheInterceptor解析
    okhttp缓存策略源码分析:put&get方法
    java线程基础巩固---ThreadGroup API学习
    通过JDBC驱动加载深刻理解线程上下文类加载器机制
    线程上下文类加载器实战分析与难点剖析
    ServiceLoader在SPI中的重要作用分析
    小试牛刀【龙哥翻译】
    小试牛刀【自己翻译】
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7246122.html
Copyright © 2011-2022 走看看