zoukankan      html  css  js  c++  java
  • balanced-binary-tree

    /**
    *
    * @author gentleKay
    * 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。
    *
    */

    在解决这道题目之前,我们必须要知道如何求一个二叉树的深度?

    public int getDepth(TreeNode root) {
    		if (root == null ) {
    			return 0;
    		}
    		int left = getDepth(root.left)+1;   //每迭代一次,深度就+1
    int right = getDepth(root.right)+1; return left > right ? left : right ; }

      我们再来分析一下题目,自从我们知道了 如何求一个二叉树的深度之后,这道题就比较简单了。

    /**
     * 
     * @author gentleKay
     * 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。
     * 
     */
    
    public class Main19 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		TreeNode root = new TreeNode(1);
    		root.left = new TreeNode(2);
    		root.left.left = new TreeNode(4);
    		root.left.right = new TreeNode(5);
    		
    		
    //		root.right = new TreeNode(3);
    //		root.right.left = new TreeNode(6);
    //		root.right.right = new TreeNode(7);
    		System.out.println(Main19.isBalanced(root));
    	}
    	
    	public static class TreeNode {
    		int val;
    		TreeNode left;
    		TreeNode right;
    		TreeNode(int x) { val = x; }
    	}
    	 
    	public static boolean isBalanced(TreeNode root) {
    		
    		if (root == null) {
    			return true;
    		}
    		
    		int left = getDepth(root.left); //拿到 相当于根节点的左右两个节点的深度
    		int right = getDepth(root.right);
    		if (Math.abs(left-right) > 1) { //并比较不超过 1 ,超过了 返回 false。
    			return false;
    		}
            return isBalanced(root.left) && isBalanced(root.right); // 在进行迭代,根节点的左右节点的左右节点进行分析深度与否。
        }
    	
    	public static int getDepth(TreeNode root) {
    		if (root == null ) {
    			return 0;
    		}
    		int left = getDepth(root.left)+1;
    		int right = getDepth(root.right)+1;
    		return left > right ? left : right ;
    	}
    
    }
    

      

  • 相关阅读:
    Scalaz(3)- 基础篇:函数概括化-Generalizing Functions
    Scalaz(2)- 基础篇:随意多态-typeclass, ad-hoc polymorphism
    Scalaz(1)- 基础篇:隐式转换解析策略-Implicit resolution
    Scalaz(0)
    泛函编程(38)-泛函Stream IO:IO Process in action
    泛函编程(37)-泛函Stream IO:通用的IO处理过程-Free Process
    泛函编程(36)-泛函Stream IO:IO数据源-IO Source & Sink
    泛函编程(35)-泛函Stream IO:IO处理过程-IO Process
    javascript基础
    jsp联合javascript操作html
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11265454.html
Copyright © 2011-2022 走看看