二叉樹概念
1.除了最下面一層,每個節點都是父節點,每個節點都有且最多有兩個子節點;
2.除了嘴上面一層,每個節點是子節點,每個節點都會有一個父節點;
3.最上面一層的節點為根節點;
圖例說明:
先序遍歷概念
先打印父節點,然后是左子節點(左子樹),然后再打印右子節點(子樹)
圖例說明:
最后貼代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> //創建二叉樹 function Node(data,left,right){ this.data = data; this.left = left; this.right = right; } Node.prototype.show = function(){ return this.data; } function BST(){ this.root = null; } BST.prototype.insert = function(data){ var node = new Node(data,null,null); if(this.root == null){ this.root = node; }else{ var current = this.root; var parent; while(true){ parent = current; if(data < current.data){ current = current.left; if(current == null){ parent.left = node; break; } }else{ current = current.right; if(current == null){ parent.right = node; break; } } } } } //二叉樹先序遍歷 BST.prototype.perOrder = function(node){ if(node){ console.log(node.show() + " "); this.perOrder(node.left); this.perOrder(node.right); } } //測試數據 var bst = new BST(); var nums = [10,3,18,2,4,13,21,9,8,9]; for(var i = 0;i < nums.length;i ++){ bst.insert(nums[i]); } bst.perOrder(bst.root); </script> </body> </html>