zoukankan      html  css  js  c++  java
  • Balanced Binary Tree

    这几天A的都是二叉树的,如果输的基本操作掌握了,用递归很好解决这些题目的。这个可能不是最好的解法,明天再去Discuss看看有没有好的解法

    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 /**
     2  * Definition for binary tree
     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      * 这里用递归实现
    13      * 如果为空节点返回true
    14      * 如果不为空比较左右子树的高度,如果高度差的绝对值小于等于1且左右子树都是平衡二叉树return true
    15      * @param root
    16      * @return
    17      */
    18     public boolean isBalanced(TreeNode root){
    19         if(null == root){
    20             return true;
    21         }else
    22         {
    23             return (Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right);
    24         }
    25         
    26     }
    27     /**
    28      * 获取一棵树的高度
    29      * 递归获取
    30      * @param root
    31      * @return
    32      */
    33     public int getHeight(TreeNode root){
    34         if(null == root)
    35             return 0;
    36         else{
    37             int max = getHeight(root.left);
    38             if(max < getHeight(root.right))
    39             {
    40                 max =getHeight(root.right);
    41             }
    42             return max + 1;
    43         }
    44     }
    45 }
  • 相关阅读:
    Apache httponly Cookie泄露

    shell脚本
    Linux与windows的文件系统结构
    使用rsync进行远程同步
    电子邮件服务
    httpd虚拟主机
    Enpass 基于 Mezzanine
    powershell: 生成随机字符串
    thinkPHP5.x 更新字段为 NULL
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4077499.html
Copyright © 2011-2022 走看看