• 110. Balanced Binary Tree Java Solutions


    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

     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         return height(root) != -1;
    13     }
    14     
    15     public int height(TreeNode t){
    16         if(t == null) return 0; //到叶子节点再往下的情况
    17         int lheight = height(t.left);
    18         int rheight = height(t.right);
    19         if(lheight == -1 || rheight == -1 || Math.abs(lheight-rheight) > 1){
    20             return -1;//使用-1 标记左右子树高度相差大于1的情况
    21         }
    22         return 1 + Math.max(lheight,rheight);
    23     }
    24 }
  • 相关阅读:
    ROS配置C++14环境
    ubantu查看环境变量
    C++指向函数的指针
    ubantu删除文件(夹)
    ROS环境搭建
    vmware workstation pro 安装ubantu虚拟机
    Win7下删除Ubuntu启动项
    ubantu16.04
    ubantu卸载软件
    github之克隆
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5450843.html
Copyright © 2020-2023  润新知