zoukankan      html  css  js  c++  java
  • 110 Balanced Binary Tree 平衡二叉树

    给定一个二叉树,确定它是高度平衡的。
    对于这个问题,一棵高度平衡二叉树的定义是:
    一棵二叉树中每个节点的两个子树的深度相差不会超过 1。
    案例 1:
    给出二叉树 [3,9,20,null,null,15,7]:
        3
       /
      9  20
        / 
       15   7
    返回 true 。
    案例 2:
    给出二叉树 [1,2,2,3,3,null,null,4,4]:
           1
          /
         2   2
        /
       3   3
      /
     4   4
    返回 false 。
    详见:https://leetcode.com/problems/balanced-binary-tree/description/

    Java实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private boolean isBalanced=true;
        public boolean isBalanced(TreeNode root) {
            if(root==null){
                return true;
            }
            getDepth(root);
            return isBalanced;
        }
        private int getDepth(TreeNode root){
            if(root==null){
                return 0;
            }
            int left=getDepth(root.left);
            int right=getDepth(root.right);
            if(Math.abs(left-right)>1){
                isBalanced=false;
            }
            return left>right?left+1:right+1;
        }
    }
    
  • 相关阅读:
    闭包
    List(数组)里面常用的属性和方法
    drat笔记
    使用dd命令克隆整个系统
    Linux dd命令
    Linux 添加PPA源
    Linux 开机自动挂载windows分区
    Linux 格式化磁盘命令mkfs
    Linux 下面adb命令的使用
    linux下面which whereis find locate的使用
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719481.html
Copyright © 2011-2022 走看看