二叉树的递归插入【Java实现】

C++中由于有指针的存在,可以让二叉树节点指针的指针作为插入函数的实参,在函数体内通过*操作实现对真实节点指针、节点左孩子指针、节点右孩子指针的改变,这样很容易使用递归将大树问题转化到小树问题。但在JAVA中,由于没有指针只有引用,如果需要递归实现二叉树的元素插入,需要对节点进行包装,同时由于递归时需要将大树问题递归到子树,包装类中的节点需要改变,但因为最后需要的是根节点,所以根节点需要备份,在递归完成后复原。下面是实现代码:

 

 1 package test;
 2 
 3 
 4 
 5 public class BiTree{
 6     
 7     public static void main(String[] args){
 8         BiTree b = new BiTree();
 9         b.operate();
10     }
11     public void operate(){
12         int[] num = {2,3,4,1,5};
13         int len = num.length;
14         //System.out.println(len);
15         Tree t = new Tree();
16         for(int i=0; i<len; i++){
17             insert(t,num[i]);
18         }
19 //        System.out.println(t.root.val );
20 //        System.out.println(t.root.right.val );
21 //        System.out.println(t.root.left.val );
22         traverse(t.root);
23         
24     }
25     
26     public void insert(Tree t, int e){
27         bNode temp = new bNode(e);
28         bNode backUp = t.root;
29         if(t.root == null){
30             t.root = temp;
31         }else{
32             if(e == t.root.val){
33                 return;
34             }else if(e<t.root.val){
35                 t.root = backUp.left;
36                 insert(t, e);
37                 backUp.left = t.root;
38                 t.root = backUp;
39                 
40             }else{
41                 t.root = backUp.right;
42                 insert(t,e);
43                 backUp.right = t.root;
44                 t.root = backUp;
45             }
46         }
47     }
48     public void traverse(bNode t){
49         if(t == null){
50             return;
51         }
52         System.out.println(t.val);
53         traverse(t.left);
54         traverse(t.right);
55         
56     }
57     
58 }
59 
60 class bNode{
61     public int val;
62     public bNode left;
63     public bNode right;
64     public bNode(int val){
65         this.val = val;
66         left = null;
67         right = null;
68     }
69 }
70 
71 class Tree{
72     public bNode root;
73     public Tree(){
74         root = null;
75     }
76 }

 

posted @ 2015-09-16 02:04  CHEN0958  阅读(2440)  评论(0编辑  收藏  举报