PS: 此算法参考资料《数据结构与算法JavaScript描述》
1 //------------------------------------------------------------------
2 //-----------------performance binary tree---------------------
3 //------------------------------------------------------------------
4 function Node(data, left, right){
5 this.data = data;
6 this.left = left;
7 this.right = right;
8 this.show = show;
9 }
10
11 function show(){
12 return this.data;
13 }
14
15 //-----------------------二叉查找树---------------------------------
16 function BST(){
17 this.root = null;
18 this.insert = insert;
19 this.inOrder = inOrder;
20 }
21
22 //------------------------insert node-------------------------------
23 function insert(data){
24 var node = new Node(data, null, null);
25 if(this.root == null){
26 this.root = node;
27 }else{
28 var current = this.root;
29 var parent;
30 while(true){
31 parent = current;
32 if(data < current.data){
33 current = current.left;
34 if(current == null){
35 parent.left = node;
36 break;
37 }
38 }
39 else{
40 current = current.right;
41 if(current == null){
42 parent.right = node;
43 break;
44 }
45 }
46
47 }
48 }
49 }
50
51 //-------------------中序遍历(升序遍历,从小到大)-------------------
52 function inOrder(node){
53 if(node != null){
54 inOrder(node.left);
55 console.log(node.show() + ' ');
56 inOrder(node.right);
57 }
58 }
59
60 //------------------中序遍历测试------------------------------------
61 var nums = new BST();
62 nums.insert(23);
63 nums.insert(45);
64 nums.insert(16);
65 nums.insert(37);
66 nums.insert(3);
67 nums.insert(22);
68 nums.insert(99);
69 console.log('Inorder traversal: ');
70 inOrder(nums.root);
71
72
73
74 //------------先序遍历(先根节点,后左节点,右节点)------------------
75 function preOrder(node){
76 if(node != null){
77 console.log(node.show());
78 preOrder(node.left);
79 preOrder(node.right);
80 }
81 }
82
83 //------------------先序遍历测试------------------------------------
84 var nums = new BST();
85 nums.insert(23);
86 nums.insert(45);
87 nums.insert(16);
88 nums.insert(37);
89 nums.insert(3);
90 nums.insert(22);
91 nums.insert(99);
92 console.log('preOrder traversal: ');
93 preOrder(nums.root);
94
95
96 //------------后序遍历(先叶子节点,后左节点,右节点,根节点)--------
97 function postOrder(node){
98 if(node != null){
99 postOrder(node.left);
100 postOrder(node.right);
101 console.log(node.show());
102 }
103 }
104
105 //------------------后序遍历测试------------------------------------
106 var nums = new BST();
107 nums.insert(23);
108 nums.insert(45);
109 nums.insert(16);
110 nums.insert(37);
111 nums.insert(3);
112 nums.insert(22);
113 nums.insert(99);
114 console.log('postOrder traversal: ');
115 postOrder(nums.root);
116 //------------------------------------------------------------------