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

来源:互联网 发布:网络流媒体地址 编辑:程序博客网 时间:2024/06/14 17:11
<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
原创粉丝点击