zoukankan      html  css  js  c++  java
  • LeetCode110 平衡二叉树

    给定一个二叉树,判断它是否是高度平衡的二叉树。

    本题中,一棵高度平衡二叉树定义为:

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

    示例 1:

    给定二叉树 [3,9,20,null,null,15,7]

        3
       / 
      9  20
        /  
       15   7

    返回 true 。

    示例 2:

    给定二叉树 [1,2,2,3,3,null,null,4,4]

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    返回 false 。

     


     

     

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    /*
    算法思想:
        根据题目中的定义,高度平衡二叉树是每一个结点的两个子树的深度差不能超过1,那么肯定需要一个求各个点深度的函数,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN)。
    */
    class Solution {
    public:
        bool isBalanced(TreeNode *root) {
            if (!root) 
                return true;
            if (abs(getDepth(root->left) - getDepth(root->right)) > 1) 
                return false;
            return isBalanced(root->left) && isBalanced(root->right);    
        }
        int getDepth(TreeNode *root) {
            if (!root) 
                return 0;
            return 1 + max(getDepth(root->left), getDepth(root->right));
        }
    };
  • 相关阅读:
    hdu 5119 Happy Matt Friends
    hdu 5128 The E-pang Palace
    hdu 5131 Song Jiang's rank list
    hdu 5135 Little Zu Chongzhi's Triangles
    hdu 5137 How Many Maos Does the Guanxi Worth
    hdu 5122 K.Bro Sorting
    Human Gene Functions
    Palindrome(最长公共子序列)
    A Simple problem
    Alignment ( 最长上升(下降)子序列 )
  • 原文地址:https://www.cnblogs.com/parzulpan/p/10090440.html
Copyright © 2011-2022 走看看