• LeetCode 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.


    题目标签:Tree

      这道题目给了我们一个 二叉树, 让我们来判断一下它是否是一个 height-balanced 二叉树。 先来看一下什么是 height-balanced 二叉树, 对于每一个点,它的左边子树的depth 和右边子树的 depth 不能相差多余1。这道题目可以利用getDepth 来帮助我们判断。getDepth function 是通过递归,利用postOrder来从树的最低端走起,当点是null时候,就返回depth 0, 每次返回depth + 1, 那么我们可以多加一个if statement 在 一个parent 点拿到左边的depth 和右边的depth 之后, 如果左边和右边的相差值,大于1,那么 把我们预先设的 boolean is_balanced 改为false。

    Java Solution:

    Runtime beats 25.84% 

    完成日期:07/03/2017

    关键词:Tree

    关键点:利用 getDepth function

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution 
    11 {
    12     boolean is_balanced = true;
    13     
    14     public boolean isBalanced(TreeNode root) 
    15     {
    16         getDepth(root);
    17         
    18         return is_balanced;
    19     }
    20     
    21     public int getDepth(TreeNode node)
    22     {
    23         if(node == null)
    24             return 0;
    25         
    26         int left_depth = getDepth(node.left);
    27         int right_depth = getDepth(node.right);
    28         
    29         if(Math.abs(left_depth - right_depth) > 1)
    30             is_balanced = false;
    31         
    32         return Math.max(left_depth, right_depth) + 1;
    33     }
    34 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    项目各方面的目标
    WPF : Imaging
    在Windows EndSession时, WPF的Shutdown()和Winforms的Application.Exit()都不可靠
    软件运行流程
    做事首先要想到的是责任和分配机制
    RhinoMocks : Stub和Mock的区别
    Visual Studio Marco : CollapseLogRegions
    使用C#实现顺序队列
    MVC 分页
    sql 行列转置(将行转换为列)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7113678.html
Copyright © 2020-2023  润新知