构造二叉搜索树并先序遍历(非递归)---java

<pre name="code" class="java">package BitTree;
import java.util.*;
public class CreateBitTree {

	/*public class BitTreeNode {
		int value;
		BitTreeNode left;
		BitTreeNode right;
		public BitTreeNode(int data){
			this.value=data;
			this.left=null;
			this.right=null;
		}
	}*/
	
	public BitTreeNode Insert(BitTreeNode root,int data){//构造二叉搜索树
		if (root==null){
			root=new BitTreeNode(data);
		}
		else{
			if(data<root.value){//值如果小于根节点,则放到左孩子节点
				root.left=Insert(root.left,data);//创建左子树
			}else{
				root.right=Insert(root.right,data);//创建右子树
			}
		}
		
		return root;
	}


	
	public void preOrder(BitTreeNode root){//先序遍历二叉树,根左右
		if(root!=null){
			System.out.print(root.value+" ");
			preOrder(root.left);
			
			preOrder(root.right);
		}
	}
	//非递归前序遍历
	public void PreScan(BitTreeNode root){
		Stack stack=new Stack();
		if(root==null) System.out.println("the tree is null");
		while(root!=null){
			while(root!=null){
				System.out.println(root.value);
				stack.push(root);//将当前子树的根节点进进栈
				//System.out.println("-"+root.left.value+"-");
				root=root.left;//访问左孩子节点				
			}
			//System.out.println("*"+root+"*");
			root=(BitTreeNode)stack.pop();//栈顶元素出栈,获得当前子树的根节点			
			root=root.right;//访问当前子树的右节点
		}
	}
	
	public static void main(String[] args){//测试代码
		int[] arr={21,13,4,45,5,6};
		BitTreeNode node=null;
		CreateBitTree bittree=new CreateBitTree();
		for(int i=0;i<arr.length;i++){
			node=bittree.Insert(node,arr[i]);
		}
		//bittree.preOrder(node);
		//System.out.println("%%"+node.right.value+"%%");
		bittree.PreScan(node);

	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值