zoukankan      html  css  js  c++  java
  • lintcode-93-平衡二叉树

    93-平衡二叉树

    给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。

    您在真实的面试中是否遇到过这个题? Yes

    样例
    给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

    二叉树A是高度平衡的二叉树,但是B不是

    标签
    分治法 递归

    思路

    采用递归的方式,判断某个结点的平衡因子(左右子树高度差)是否大于1,若平衡因子大于1,则其一定不是平衡二叉树,否则,继续判断。

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root: The root of binary tree.
         * @return: True if this Binary tree is Balanced, or false.
         */
        bool isBalanced(TreeNode *root) {
            // write your code here
            // write your code here
            return isSubTreeBalanced(root) != -1;
        }
    
        int isSubTreeBalanced(TreeNode *root) {
            if(root == NULL) {
                return 0;
            }
    
            int left = isSubTreeBalanced(root->left);
            int right = isSubTreeBalanced(root->right);
            
            if(left == -1 || right == -1 || abs(left - right) > 1) {
                return -1;
            }
            else {
                return (left > right ? left : right) + 1;
            }
        }
    };
    
  • 相关阅读:
    01点睛Spring MVC 4.1-搭建环境
    18点睛Spring4.1-Meta Annotation
    17点睛Spring4.1-@Conditional
    16点睛Spring4.1-TaskScheduler
    15点睛Spring4.1-TaskExecutor
    Zabbix4.0.3解决中文乱码
    A10映射方法
    源码安装zabbix_agent4.0.3
    单机部署redis5.0集群环境
    zabbix系列之九——添加钉钉告警
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7150116.html
Copyright © 2011-2022 走看看