This article mainly introducesJavaScriptto implement the recursive traversal and non-recursive traversal algorithms of multi-trees, and analyzes in detail the recursive and non-recursive traversal related operations of JavaScript multi-trees for json nodes in the form of examples. Tips, friends who are interested in JavaScript can refer to
This article describes the example of JavaScript implementing recursive traversal and non-recursive traversal algorithm operations of multi-trees. Share it with everyone for your reference, the details are as follows:
Preparation work before demonstration
Demo project File structure:
index.htmljsonData.js
recurrenceTree.js
noRecurrenceTree.js
Explain each file:
index.html is the HTML file used for demonstration.jsonData.js stores the JSON data of multi-tree.
recurrenceTree.js Recursive algorithm traverses the tree.
noRecurrenceTree.js Non-recursive algorithm for tree traversal.
/** * 用于演示的 JSON 树形数据结构 */ var root = { name:'D盘', children:[ { name:'学习', children:[ { name:'电子书', children:[ { name:'文学', children:[ { name:'茶馆' }, { name:'红与黑' } ] } ] } ] }, { name:'电影', children:[ { name:'美国电影' }, { name:'日本电影' } ] } ] }
m.sbmmt.com js多叉树遍历 递归遍历:
非递归遍历:
Recursive traversal
recurrenceTree.js// 遍历单个节点 function traverseNode(node){ var pObj = document.getElementById("app"); pObj.innerHTML = pObj.innerHTML + " " + node.name; } // 递归遍历树 // 作者:张超 function traverseTree(node){ if (!node) { return; } traverseNode(node); if (node.children && node.children.length > 0) { var i = 0; for (i = 0; i < node.children.length; i++) { this.traverseTree(node.children[i]); } } } traverseTree(root);
Non-recursive traversal##noRecurrenceTree.js
// 遍历单个节点 function traverseNode2(node){ var pObj2 = document.getElementById("app2"); pObj2.innerHTML = pObj2.innerHTML + " " + node.name; } // 非递归遍历树 // 作者:张超 function traverseTree2(node){ if (!node) { return; } var stack = []; stack.push(node); var tmpNode; while (stack.length > 0) { tmpNode = stack.pop(); traverseNode2(tmpNode); if (tmpNode.children && tmpNode.children.length > 0) { var i = tmpNode.children.length - 1; for (i = tmpNode.children.length - 1; i >= 0; i--) { stack.push(tmpNode.children[i]); } } } } traverseTree2(root);
The above is all the content of this article, I hope it can be useful Learning JavaScript helps everyone! !
Related recommendations:
This article is mainly for everyone A detailed introduction to the functions of the js lottery system on a topic about the lottery system, which has a certain reference price....
This article mainly Let me introduce to you the relevant information about the detailed explanation of ajax access examples in native js. I hope that through this article you can master the theory....
The above is the detailed content of Examples of JavaScript implementation of recursive traversal and non-recursive traversal algorithms for multi-trees. For more information, please follow other related articles on the PHP Chinese website!