二叉树深度优先遍历和广度优先遍历——JavaScript
// 1、深度优先遍历的递归写法 var nodes = []; function deepTraversal(node) { if (node != null) { nodes.push(node); var children = node.children; for (var i = 0; i < children.length; i++) deepTraversal(children[i]); } } // 2、深度优先遍历的非递归写法 var nodes = []; function deepTraversal(node) { if (node != null) { var stack = []; stack.push(node); while (stack.length != 0) { var item = stack.pop(); nodes.push(item); var children = item.children; for (var i = children.length - 1; i >= 0; i--) stack.push(children[i]); } } } // 3、广度优先遍历的非递归写法 var nodes = []; function wideTraversal(node) { if (node != null) { var stack = []; stack.push(node); while (stack.length != 0) { var item = stack.shift(); nodes.push(item); var children = item.children; for (var i = 0; i < children.length; i++) stack.push(children[i]); } } }