算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现
生活随笔
收集整理的這篇文章主要介紹了
算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
結(jié)點(diǎn):
function Node(data, left, right) {this.data = data;this.left = left;this.right = right;this.show = show; }顯示樹的數(shù)據(jù):
function show(){return this.data; }二叉查找樹:
// Binary Search Tree function BST(){this.root = null;this.insert = insert; }添加結(jié)點(diǎn)到二叉樹:
function insert(data){let n = new Node(data, null, null)if(this.root == null){this.root = n;}else{let current = this.root;let parent;while(true){parent = current;if(data < current.data){current = current.left;if(current == null){parent.left = n;breakk}}else{current = current.rightif(current == null){parent.right = n;break;}}}} }生成二叉查找樹:
function genBST(list){if(list.length>0){let t = new BST();list.forEach((data)=>{t.insert(data);})return t} } let list = [2,3,4,1]; console.log(genBST(list));先序遍歷:
function DLR(t){if(t.root !== undefined){console.log(t.root.data);if(t.root.left !== null){DLR(t.root.left)}if(t.root.right!==null){DLR(t.root.right)}}else{if(t !== null){console.log(t.data);if(t.left !== null){DLR(t.left)}if(t.right!==null){DLR(t.right)}}} }let list = [1,2,3,6,5,4]; let t = genBST(list); DLR(t);
中序遍歷:
后續(xù)遍歷:
參考https://github.com/zoro-web/blog/issues/4
總結(jié)
以上是生活随笔為你收集整理的算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1415C. Bouncing Ball
- 下一篇: 打印机提示更换墨盒,但打印字仍很清晰,打