日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

結點:

function Node(data, left, right) {this.data = data;this.left = left;this.right = right;this.show = show; }

顯示樹的數據:

function show(){return this.data; }

二叉查找樹:

// Binary Search Tree function BST(){this.root = null;this.insert = insert; }

添加結點到二叉樹:

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);


中序遍歷:

function LDR(t){if(t.root !== undefined){if(t.root.left !==null){LDR(t.root.left)}console.log(t.root.data);if(t.root.right !== null){LDR(t.root.right)}}else{if(t !==null){if(t.left !== null){LDR(t.left);}console.log(t.data);if(t.right !== null){LDR(t.right);}}} }let list = [1,2,3,6,5,4]; let t = genBST(list); LDR(t);


后續遍歷:

function LRD(t){if(t.root !== undefined){if(t.root.left !==null){LRD(t.root.left)}if(t.root.right !== null){LRD(t.root.right)}console.log(t.root.data);}else{if(t !==null){if(t.left !== null){LRD(t.left);}if(t.right !== null){LRD(t.right);}console.log(t.data);}} }let list = [1,2,3,6,5,4]; let t = genBST(list); LRD(t);

參考https://github.com/zoro-web/blog/issues/4

總結

以上是生活随笔為你收集整理的算法 --- 二叉树查找树的先序(中序、后序)遍历的js实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。