js实现创建二叉树+先序遍历
生活随笔
收集整理的這篇文章主要介紹了
js实现创建二叉树+先序遍历
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
二叉樹概念
1.除了最下面一層,每個節(jié)點都是父節(jié)點,每個節(jié)點都有且最多有兩個子節(jié)點;
2.除了嘴上面一層,每個節(jié)點是子節(jié)點,每個節(jié)點都會有一個父節(jié)點;
3.最上面一層的節(jié)點為根節(jié)點;
圖例說明:
先序遍歷概念
先打印父節(jié)點,然后是左子節(jié)點(左子樹),然后再打印右子節(jié)點(子樹)
圖例說明:
?
最后貼代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title> </head> <body><script>//創(chuàng)建二叉樹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);}}//測試數(shù)據(jù)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>?
轉(zhuǎn)載于:https://www.cnblogs.com/xiaohualu/p/10308071.html
總結(jié)
以上是生活随笔為你收集整理的js实现创建二叉树+先序遍历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 WIndows,Linux 以及
- 下一篇: [CQOI2018] 异或序列