判断二叉树是否是搜索二叉树和完全二叉树

import java.util.*;
//判断二叉树是否是搜索二叉树和完全二叉树
public class isTree{
	
	//二叉树节点的定义
	public  static class  Node{

		public int value;
		public Node left;
		public Node right;

		public Node(int data)
		{

			this.value=data;
		}
	} 

	//判断是否是搜索二叉树(中序遍历递增)
	public static boolean isBST(Node head)
	{
          if(head==null)
          {
          	return true;
          }
          boolean res=true;
          Node pre=null;
          Node cur1=head;
          Node cur2=null;
          while(cur1!=null)
          {
              cur2=cur1.left;
              if(cur2!=null)
              {
                  while(cur2.right!=null&&cur2.right!=cur1)
                  {
                  	cur2=cur2.right;
                  }
                  if(cur2.right==null)
                  {
                  	cur2.right=cur1;
                  	cur1=cur1.left;
                  	continue;
                  }else
                  {
                  	 cur2.right=null;
                  }
              }
              if(pre!=null&&pre.value>cur1.value)
              {
              	res=false;
              }
              pre=cur1;
              cur1=cur1.right;

          }
          return res;


	}
 
    //判断是否是完全二叉树
    /**
     (1)层序遍历所有节点
     (2)当前节点有右孩子,没有左孩子 false
     (3)当前节点不是左右孩子都有,则为叶节点,否则false
    */
    public static boolean isCBT(Node head)
    {
       if(head==null)
       {
       	return true;
       }
       Queue<Node>queue=new LinkedList<Node>();
       boolean leaf=false;
       Node l=null;
       Node r=null;
       queue.offer(head);
       while(!queue.isEmpty())
       {
       	  head=queue.poll();
       	  l=head.left;
       	  r=head.right;
       	  if((leaf&&(l!=null||r!=null))||(l==null&&r!=null))
       	  {
       	  	return false;
       	  }
       	  if(l!=null)
       	  {
       	  	queue.offer(l);
       	  }
       	  if(r!=null)
       	  {
       	  	 queue.offer(r);
       	  }
       	  else
       	  {
       	  	 leaf=true;
       	  }
       }
           
        return true;


      
    }

	public static void main(String []args)
	{
          /**
                    4
                2      6
              1   3   5
            */
            Node head=new Node(4);
            head.left=new Node(2);
            head.right=new Node(6);
            head.left.left=new Node(1);
            head.left.right=new Node(3);
            head.right.left=new Node(5);

            System.out.println(isBST(head));
            System.out.println(isCBT(head));

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值