• 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;
        }
    
    }
  • 相关阅读:
    Vue-router的实现原理
    get请求被浏览器跨域的同源策略请求机制拦截,但是get请求是否请求到了服务器呢
    合并两个有序链表
    JS实现链式调用 a().b().c()
    CSS知识点总结
    BK-信息查找、摘取
    radar图生成用户guideline
    【转】 mybatis 详解(七)------一对一、一对多、多对多
    【转】 mybatis 详解(六)------通过mapper接口加载映射文件
    【转】 mybatis 详解(五)------动态SQL
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7246122.html
Copyright © 2020-2023  润新知