zoukankan      html  css  js  c++  java
  • 平衡二叉树

    平衡二叉树的定义:

    如果每一个节点的左子树和右子树的高度差不超过1,那么这可树就是平衡二叉树。

    判断一个树是否为平衡树,把握三点。

    (1)左子树是否平衡 (2)右子树是否平衡 (3)左子树的高度和右子树的高度差值低于1

    递归的套路

    package class_04;
    
    public class Code_06_IsBalancedTree {
    
    	public static class Node {
    		public int value;
    		public Node left;
    		public Node right;
    
    		public Node(int data) {
    			this.value = data;
    		}
    	}
    
    	public static class ReturnData{
    		public boolean isB;   // 是否平衡
    		public int h;         // 该节点的高度
    		public ReturnData(boolean isB, int h) {
    			this.isB = isB;
    			this.h = h;
    		}
    	}
    	
    	/*
    	 * 思路:判断一个树是否为平衡树,(1)左子树是否平衡 (2)右子树是否平衡 (3)左子树的高度和右子树的高度差值低于1
    	 * */
    	public static ReturnData process(Node node) {
    		if(node == null) {                       // 判断是否为空,空树是平衡的
    			return new ReturnData(true, 0);
    		}
    		
    		ReturnData leftData= process(node.left); // 判断左子树是否平衡
    		if(!leftData.isB) {
    			return new ReturnData(false, 0);
    		}
    		
    		ReturnData rightData= process(node.left); // 判断右子树是否平衡
    		if(!rightData.isB) {
    			return new ReturnData(false, 0);
    		}
    		
    		if(Math.abs(leftData.h - rightData.h) > 1) { // 如果左子树和右子树的高度值差超过1
    			return new ReturnData(false, 0);
    		}
    		
    		return new ReturnData(true, Math.max(leftData.h, rightData.h) + 1);  // 往下走高度+1
    	}
    	
    	public static boolean isBalance(Node head) {
    		boolean[] res = new boolean[1];
    		res[0] = true;
    		getHeight(head, 1, res);
    		return res[0];
    	}
    
    	public static int getHeight(Node head, int level, boolean[] res) {
    		if (head == null) {
    			return level;
    		}
    		int lH = getHeight(head.left, level + 1, res);
    		if (!res[0]) {
    			return level;
    		}
    		int rH = getHeight(head.right, level + 1, res);
    		if (!res[0]) {
    			return level;
    		}
    		if (Math.abs(lH - rH) > 1) {
    			res[0] = false;
    		}
    		return Math.max(lH, rH);
    	}
    
    	public static void main(String[] args) {
    		Node head = new Node(1);
    		head.left = new Node(2);
    		head.right = new Node(3);
    		head.left.left = new Node(4);
    		head.left.right = new Node(5);
    		head.right.left = new Node(6);
    		head.right.right = new Node(7);
    
    		System.out.println(isBalance(head));
    
    	}
    
    }
    
  • 相关阅读:
    Linux下安装MySQL数据库(压缩包方式安装)
    使用Gitblit 在windows 上部署你的Git Server
    windows下使用docker的常用命令
    CentOS7安装Docker与使用篇
    linux安装redis
    Linux系统目录
    shiro之授权
    shiro之身份认证
    redis
    迅为4412uboot烧坏了报错问题
  • 原文地址:https://www.cnblogs.com/horken/p/10706129.html
Copyright © 2011-2022 走看看