( Leetcode 110 ) Balanced Binary Tree

题目: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,一次我们可以设置一个求树高度的函数,用来求任意树的高度,然后判定给定的子节点子树的高度差,如果大于1则不是平衡二叉树,否则就是平衡二叉树。使用递归来实现


具体看下面的Java代码:

public class Solution {
   public boolean isBalanced( TreeNode root ){
		if( root == null ){
			return true;
		}
		int left = depth(root.left, 1);
		int right = depth(root.right, 1);
		if( Math.abs(left-right) > 1 ){
			return false;
		}
		return ( isBalanced(root.left) && isBalanced(root.right) );
	}
	
	public int depth( TreeNode root, int dep ){
		if( root == null ){
			return dep;
		}
		int left = depth(root.left, dep+1);
		int right = depth(root.right, dep+1);
		
		return left > right ? left : right;
	}

}



你可能感兴趣的:(数据结构与算法,java)