55.判断平衡二叉树

题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1 ,那么它就是一棵平衡二叉树。

基本思路:

解法一:需要遍历结点多次的解法 在遍历树的每个结点的时候,调用函数treeDepth得到它的左右子树的深度。如果每个结点的左右子树的深度相差都不超过1 ,按照定义它就是一棵平衡的二叉树。

解法二:每个结点只遍历一次的解法 用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度(某一结点的深度等于它到叶节点的路径的长度),我们就可以一边遍历一边判断每个结点是不是平衡的

解法一Java实现:

public class IsBalancedTree {
	 private static class BinaryTreeNode {
	        int val;
	        BinaryTreeNode left;
	        BinaryTreeNode right;

	        public BinaryTreeNode() {
	        }

	        public BinaryTreeNode(int val) {
	            this.val = val;
	        }
	    }

	public static boolean isBalancedTree(BinaryTreeNode root) {
		if(root==null) {
			return true;
		}
		int left=treeDepth(root.left);
		int right=treeDepth(root.right);
		if(Math.abs(left-right)>1) {
			return false;
			
		}
		return  isBalancedTree(root.left)&&isBalancedTree(root.right);
		
	}

	//求当前节点的深度
	private static int treeDepth(BinaryTreeNode root) {
		// TODO Auto-generated method stub
		if(root==null) {
			return 0;
		}
		int left=treeDepth(root.left);
		int right=treeDepth(root.right);
		return left>right?left+1:right+1;
	}
}

解法二Java实现:

public class IsBalancedTree{
	private static class BinaryTreeNode {
        int val;
        BinaryTreeNode left;
        BinaryTreeNode right;

        public BinaryTreeNode() {
        }

        public BinaryTreeNode(int val) {
            this.val = val;
        }
    }
	
	public static boolean isBalancedTree(BinaryTreeNode root) {
		int[] depth = new int[1];
        return isBalancedHelper(root, depth);
	}

	private static boolean isBalancedHelper(BinaryTreeNode root, int[] depth) {
		// TODO Auto-generated method stub
		if (root == null) {
            depth[0] = 0;
            return true;
        }

        int[] left = new int[1];
        int[] right = new int[1];

        //后序遍历
        if (isBalancedHelper(root.left, left) && isBalancedHelper(root.right, right)) {
            int diff = left[0] - right[0];
            if (diff >= -1 && diff <= 1) {
                depth[0] = 1 + (left[0] > right[0] ? left[0] : right[0]);
                return true;
            }
        }

        return false;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值