zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】树题5:110 Balanced Binary Tree

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    110. Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.
    For this problem, a height-balanced binary tree is defined as:
    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
    Example 1:
    Given the following tree [3,9,20,null,null,15,7]:
    Return true.
     
    Example 2:
    Given the following tree [1,2,2,3,3,null,null,4,4]:
    Return false.
     
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    /*
    对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,
    如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1
    此方法时间复杂度O(N),空间复杂度O(H)
     
    对于用递归求解的题,可以画递归树来分析
    */
    class Solution
    {
    public:   
        bool isBalanced(TreeNode *root)
        {
            if (checkDepth(root) == -1) return false;
            else return true;
        }
       
        //类似问题:104. Maximum Depth of Binary Tree
        int checkDepth(TreeNode *root)
        {
            if (!root) return 0; //为空时,返回深度
           
            int left = checkDepth(root->left); //返回左子树的深度,如果不平衡,返回-1
            if (left == -1) return -1; //只要哪里有-1一路返回,直到递归结束
           
            int right = checkDepth(root->right); //返回右子树的深度
            if (right == -1) return -1;
           
            int diff = abs(left - right); //计算左右子树的深度差,如果不平衡,返回-1,平衡则返回实际深度
            if (diff > 1)
                return -1;
            else
                return 1 + max(left, right);
        }
    };
     
  • 相关阅读:
    安卓学习记录(四)——体温表APP
    2012ACM/ICPC亚洲区域赛成都赛区 总结
    poj 1011 Sticks(dfs+剪枝)
    uva 10891 Game of Sum (DP水题)
    poj 1077 Eight (bfs+康拓展开,A*&&IDA*算法)
    USACO Shaping Regions(离散化)
    poj 2741 Colored Cubes(dfs暴力枚举)
    LightOJ 1400 Employment (Stable Marriage)
    uva 10859 Placing Lampposts / Tree DP
    poj 1062 昂贵的聘礼(dfs+剪枝)
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225786.html
Copyright © 2011-2022 走看看