您的位置:首页 > 其它

计算二叉树的深度,判断二叉树是否是平衡二叉树

2015-07-07 20:49 459 查看
package java_study.JianZhiOffer;

import org.junit.Test;

/**
* Created by ethan on 2015/7/7.
* 剑指offer No39计算二叉树的深度,判断二叉树是否是平衡二叉树
*/
public class No39二叉树的深度 {

public int getDepth(TreeNode root){
if (root == null) return 0;
int left = getDepth(root.getLchild());
int right = getDepth(root.getRchild());
return (left>right?left:right)+1;
}
// 判断平衡二叉树的方法1: 先序的方法,这样重复遍历了
public boolean isBalanceBinaryTree(TreeNode root){
if (root==null) return true;
int left = getDepth(root.getLchild());
int right = getDepth(root.getRchild());
int gap = left - right;
if (Math.abs(gap)<=1){
return isBalanceBinaryTree(root.getLchild()) && isBalanceBinaryTree(root.getRchild());
}else
return false;
}
// 判断平衡二叉树的方法2: 后序的方法,这样就不需要重复遍历了
// 但是这样就要在根节点和子节点传递深度,如果用c/c++的指针实现比较简单,用java实现实在是ugly
public class Depth{
int depth;
}
public boolean isBanlanceBinaryTreePost(TreeNode root){
return isBanlanceBinaryTreePostImp(root, new Depth());
}
public boolean isBanlanceBinaryTreePostImp(TreeNode root, Depth d){
if (root==null) {
d.depth = 0;
return true;
}
Depth d_left = new Depth();
Depth d_right = new Depth();
if (isBanlanceBinaryTreePostImp(root.getLchild(), d_left) && isBanlanceBinaryTreePostImp(root.getRchild(), d_right)){
int gap = d_left.depth - d_right.depth;
if (Math.abs(gap)<=1){
d.depth = ((d_left.depth>d_right.depth)?d_left.depth:d_right.depth)+1;
return true;
}
}
return false;
}

@Test
public void test(){
TreeNode root = TreeUtil.buildTree("478321", "872341");
TreeUtil.postOrder(root);
System.out.println();
System.out.println(getDepth(root));
System.out.println(isBalanceBinaryTree(root));
System.out.println(isBanlanceBinaryTreePost(root));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息