/* *@Params: data --节点数据 children -- 所有孩子结点 */ function TreeNode(data, children){ if(!(this instanceof TreeNode)){ return new TreeNode(data, children); } this.data = data || null; this.children = children || []; };
根据上述TreeNode构造函数,我们可以将例子中的树,表示如下:
var treeNode = TreeNode('A', [ TreeNode('B', [TreeNode('E')]), TreeNode('C'), TreeNode('D') ]);
接着,就是编写遍历树方法咯,分别为先根遍历和按层次遍历,如下:
TreeNode.prototype = { constructor: TreeNode, _traverseAsDFS: function(node){//先根遍历 var self = this; if(node){ console.log(node.data); node.children.forEach(function(child){ if(child.children.length){ self._traverseAsDFS(child); }else{ console.log(child.data); } }); } }, traverseAsDFS: function(){ console.log('Depth_First Search'); this._traverseAsDFS(this); }, traverseAsBFS: function(){//按层次遍历 var queue = []; console.log('Breadth_First Search'); console.log(this.data); if(this.children.length){ queue.push(this); } while(queue.length){ let tempNode = queue.shift(); tempNode.children.forEach(function(child){ console.log(child.data); if(child.children.length){ queue.push(child); } }); } } };
好了,利用上述二叉树例子,我们可以自行测试下:
var treeNode = TreeNode('A', [ TreeNode('B', [TreeNode('E')]), TreeNode('C'), TreeNode('D') ]); treeNode.traverseAsDFS();//ABECD treeNode.traverseAsBFS();//ABCDE
关于上述全部代码,见。