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

非递归方法,基本是层次遍历二叉树 依次检查每一个节点:

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));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值