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

    思路:求每个节点左右子树的高度,如果  H左树 - H 右树大于 1 或者 H 右树 - H 左树大于 1 ,就返回false ,为此,我另写了个求高度的辅助函数。这么做

    我觉得效率有点低。。。但是第一反应就想到的这个。回头看看网上别的大神有没更高效的方法。。

     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 class Solution {
    11     public boolean isBalanced(TreeNode root) {
    12         int lHeight,rHeight;
    13         if (root==null)
    14             return true;                    //如果一开始传进来一个空引用,则返回true
    15         else{
    16             lHeight = getHeight(root.left);        //求左树高和右树高
    17             rHeight = getHeight(root.right);
    18             if (lHeight-rHeight>1||rHeight-lHeight>1)
    19                 return false;                              //不满足平衡条件,返回false;
    20             else{
    21                 //满足的话,递归判断左右孩子是否满足条件。左右孩子也可能不满足条件
    22                 //,所以要递归判断。想象下人字形树。
    23                 return isBalanced(root.left)&&isBalanced(root.right);
    24             }
    25         }
    26     }
    27     public int getHeight(TreeNode root){
    28         int lHeight=0,rHeight=0;
    29         if (root==null)
    30             return 0;
    31         else {
    32             lHeight = getHeight(root.left);
    33             rHeight = getHeight(root.right);
    34         }
    35         if (lHeight<rHeight)
    36             lHeight = rHeight;
    37         return lHeight+1;
    38     }
    39 }
  • 相关阅读:
    策略梯度(Policy Gradient)
    无约束优化问题
    有约束优化问题
    计算机网络学习资料
    为什么要用等效基带信号?
    通信网实验—话务量分析
    无感数据埋点(自定义注解+aop+异步)
    排序算法
    位运算常见操作
    数据库与缓存一致性的几种实现方式
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7716354.html
Copyright © 2020-2023  润新知