<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);
}
}
构造二叉搜索树并先序遍历(非递归)---java
最新推荐文章于 2021-03-31 21:51:45 发布