您的位置:首页 > 其它

判断一棵二叉树是否为完全二叉树

2014-10-28 21:08 316 查看
非递归方法,基本是层次遍历二叉树 依次检查每一个节点:

1.当发现有一个节点的左子树为空,右子树不为空时 直接返回false.

2.当发现有一个节点的左子树不为空,右子树为空时,置标志位为1。

3.当发现有一个节点的左右子树均为空时,置标志位为1。

标志位为1的作用是,标记此节点以下的节点均应为叶子节点(没有左右孩子),否则此树为一棵非完全二叉树。

代码如下:

package treeInfo;
import java.util.LinkedList;

class Node{
public Node left;
public Node right;
public int data;
public Node(int data) {
super();
this.data = data;
}

public Node(Node left, Node right, int data) {
super();
this.left = left;
this.right = right;
this.data = data;
}

@Override
public String toString() {
return "Node [data=" + data + "]";
}

}

class MyQueue<Node> extends LinkedList<Node>{
public Node pop(){
return removeLast();
}

public void push(Node node){
super.addFirst(node);
}

public int size(){
return super.size();
}
}

public class CompleteBinaryTree {
//检查一棵树是不是完全二叉树
public static boolean checkBTree(Node root){
if(root==null){
System.out.println("空树!");
return true;
}
MyQueue<Node> queue=new MyQueue<Node>();
queue.push(root);
Node temp;
int flag=0;
while(queue.size()>0){
temp=queue.pop();
if(null!=temp.left){
if(1==flag){
return false;
}
queue.push(temp.left);
if(null!=temp.right){
queue.push(temp.right);
}else{
flag=1;
}
}else{
if(null!=temp.right){
return false;
}
flag=1;
}

}

return true;
}
//生成一颗二叉树
public static void buildTree(Node root){
Node now;
Node left=new Node(2);
Node right=new Node(3);
root.left=left;
root.right=right;
left=new Node(4);
right=new Node(5);
now=root.left;
now.left=left;
now.right=right;
left=new Node(6);
right=new Node(7);
now=root.right;
now.left=left;
now.right=right;

left=new Node(8);
right=new Node(9);

now=root.left.left;
now.left=left;
//now.right=right;

// now=root.left.right;
// now.left=new Node(10);
}

//测试用主函数
public static void main(String[] args) {
// TODO Auto-generated method stub
Node root=new Node(1);
buildTree(root);
System.out.println(checkBTree(root));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: