# 如何只遍历一次判断一棵二叉树是否为平衡二叉树

311人阅读 评论(0)

现在要只遍历一次判断一棵二叉树是否为平衡二叉树，这个问题可以这样分析，假设p为二叉树中的任何一个节点，f(p)表示以p为根节点的子树是否为平衡二叉树，则f(p)满足

1，当p不为null时，则f(p)为真，当且仅当f(pleft)为真，且f(pright)为真，且pleft和priht的深度之差小于等于1。否则f(p)为false。pleft表示p的左孩子节点，pright表示p的右孩子节点。

2，当p为null时，则f(p)为真。

java代码如下，包括测试代码和核心代码

package AlgorithmTest;

/**
* Created by dell on 2015/11/20.
*/
public class JudgeIsBalanceBinaryTreeUtil {
public static void main(String[] args) {
BinarySearchTree binarySearchTree = new BinarySearchTree();
binarySearchTree.insertNode(4);
binarySearchTree.insertNode(1);
binarySearchTree.insertNode(5);//这个二叉排序树为二叉平衡术，因此判断应该为真
if(JudgeBalanceBinaryTree(binarySearchTree.getRootNode())){
System.out.println("is balanced binary tree");
}else{
System.out.println("not balanced binary tree");
}
}

public static boolean JudgeBalanceBinaryTree(Node root){
return isBalanceBinaryTree(root).isBalanced;
}
public static Result isBalanceBinaryTree(Node root){
Result result = new Result();

if (null == root){
result.depth = 0;
result.isBalanced = true;
return result;
}

Result leftResult = isBalanceBinaryTree(root.nodeLeft);
if (leftResult.isBalanced){
Result rightResult = isBalanceBinaryTree(root.nodeRight);
if (rightResult.isBalanced){
int diff = leftResult.depth - leftResult.depth;
if (diff <= 1 && diff >= -1){
result.isBalanced = true;
result.depth = 1 + (leftResult.depth > rightResult.depth ? leftResult.depth : rightResult.depth);
return result;
}
}
}

result.isBalanced = false;
return result;
}

private static class Result{
private boolean isBalanced;
private int depth;

public Result(){
isBalanced = false;
depth = 0;
}
public int getDepth() {
return depth;
}

public void setDepth(int depth) {
this.depth = depth;
}

public boolean isBalanced() {
return isBalanced;
}

public void setIsBalanced(boolean isBalanced) {
this.isBalanced = isBalanced;
}
}

}



0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：38071次
• 积分：1030
• 等级：
• 排名：千里之外
• 原创：70篇
• 转载：0篇
• 译文：0篇
• 评论：0条
阅读排行