zoukankan      html  css  js  c++  java
  • LeetCode OJ 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.

    做完了链表系列,这几天开始做树系列。对于解决关于树的问题,递归是一个很好的方法。对于这个题目我们也可以用递归来解决,给定一个节点,我们分别判断它的左子树是否平衡,右子树是否平衡。如果它的子树有不平衡的,那么该树是不平衡的。如果它的子树平衡,我们要比较一下两个子树深度差是否超过1。如果超过1,那么该树也是不平衡的。如何记录节点的深度呢,我们可以利用节点中的val来存储一个节点和它的子树组成的树的深度。是不是很巧妙呢?代码如下:

     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     public boolean isBalanced(TreeNode root) {
    12         if(root == null) return true;
    13         if(root.left == null && root.right == null){
    14             root.val = 1;
    15             return true;
    16         }
    17         
    18         int leftdeep = 0;
    19         int rightdeep = 0;
    20         if(root.left != null){
    21             if(!isBalanced(root.left)) return false;
    22             leftdeep = root.left.val;
    23         }
    24         if(root.right != null){
    25             if(!isBalanced(root.right)) return false;
    26             rightdeep = root.right.val;
    27         }
    28         
    29         if(Math.abs(leftdeep - rightdeep) > 1) return false;
    30         root.val = leftdeep>rightdeep?leftdeep+1:rightdeep+1;
    31         return true;
    32     }
    33 }
  • 相关阅读:
    HTML5 drag拖动事件
    echarts 实现立体柱子图
    团队管理(七)
    echarts环比图实现
    父组件调用图表组件根据按钮切换展示数据
    echarts 折柱图绘制图表标注
    团队管理(六)
    团队管理(五)
    css 绘制圆角三角形
    团队管理(四)
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5432524.html
Copyright © 2011-2022 走看看