zoukankan      html  css  js  c++  java
  • 110. Balanced Binary Tree

    1. 问题描述

    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.
    Subscribe to see which companies asked this question
    Tags: Tree, Depth-first Search
    Similar Problems: (E) Maximum Depth of Binary Tree

    2. 解题思路

    • 先求左右子树的深度,再递归判断

    3. 代码

    class Solution {
    public:
        bool isBalanced(TreeNode* root) 
        {
            if (NULL == root)
            {
                return true;
            }
            int ld = getBinaryDepth(root->left);
            int rd = getBinaryDepth(root->right);
            if (ld-rd>1 || rd-ld>1)
            {
                return false;
            }
            else
            {
                return isBalanced(root->left) && isBalanced(root->right);
            }
        }
    private:
        int getBinaryDepth(TreeNode* root)
        {
            if (NULL == root)
            {
                return 0;
            }
            int ld = 1 + getBinaryDepth(root->left);
            int rd = 1 + getBinaryDepth(root->right);
            return ld > rd ? ld : rd;
        }
    };

    4. 反思

    • 在CSDN上发现一种做法,可以把时间复杂度降低为O(N)
    • http://blog.csdn.net/feliciafay/article/details/18348065
  • 相关阅读:
    Android 引用资源
    Android res目录结构
    Android 目录结构
    ubuntu 14.04 (desktop amd 64) 查看配置参数
    ros service
    install ros-indigo-map-server
    python 单例
    查看指定目录空间占用
    shell 设置超时时间
    nohup 不生成 nohup.out的方法
  • 原文地址:https://www.cnblogs.com/whl2012/p/5782115.html
Copyright © 2011-2022 走看看