剑指offer-平衡二叉树

题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题思路:中序遍历得到左右子树的深度,判断左右子树的深度差是否大于1,若小于1则为平衡树,否则不是;这种方法会使得每个节点递归遍历多次,消耗大。后序遍历每个节点只会遍历到一次,先判断左右子树是否为平衡树,再得到树的深度。

中序遍历:

public class Solution {
   public boolean IsBalanced_Solution(TreeNode root) {
		 if(root==null){
	    	   return true;
	       } 
		 int left = treeDept(root.left);
		 int right = treeDept(root.right);
		 int diff = left - right;
		 if(diff>1||diff<-1){
			 return false;
		 }
	       
		 return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
	       
	 }

	private int treeDept(TreeNode root) {
		// TODO Auto-generated method stub
		if(root==null){
			return 0;
		}
		int left = treeDept(root.left);
		int right = treeDept(root.right);
		return (left>right?left:right)+1;
	}
}

后序遍历:

public class JZ42 {
	private boolean isBalanced = true;
	 public boolean IsBalanced_Solution(TreeNode root) {
		treeDept(root);
		return isBalanced;
	       
	 }

	private int treeDept(TreeNode root) {
		// TODO Auto-generated method stub
		if(root==null){
			return 0;
		}
		int left = treeDept(root.left);
		int right = treeDept(root.right);
		
		if(Math.abs(left-right)>1){
			isBalanced = false;
		}
		return right>left?right+1:left+1;
	}
}

你可能感兴趣的:(剑指offer)