深度优先遍历(Depth-First Search)

递归版本
function deepFirstSearch(node,nodeList) {
if (node) {
nodeList.push(node);
var children = node.children;
for (var i = 0; i < children.length; i++)
deepFirstSearch(children[i],nodeList);
}
return nodeList;
}
非递归版本
function deepFirstSearch(node) {
var nodes = [];
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]);
}
}
return nodes;
}
广度优先遍历(breadth-first traverse)

递归版本
function breadthFirstSearch(node) {
var nodes = [];
var i = 0;
if (!(node == null)) {
nodes.push(node);
breadthFirstSearch(node.nextElementSibling);
node = nodes[i++];
breadthFirstSearch(node.firstElementChild);
}
return nodes;
}
非递归版本
function breadthFirstSearch(node) {
var nodes = [];
if (node != null) {
var queue = [];
queue.unshift(node);
while (queue.length != 0) {
var item = queue.shift();
nodes.push(item);
var children = item.children;
for (var i = 0; i < children.length; i++)
queue.push(children[i]);
}
}
return nodes;
}
二叉树相关
前序遍历(不使用递归)
preorder(root){
if(!root){
return [];
}
var result = []
var stack = [root]
while(stack.length!==0){
var top = stack.pop();
if(top.right){
stack.push(top.right);
}
if(top.left){
stack.push(top.left);
}
result.push(top.element);
}
return result;
}
中序遍历(不使用递归)
inorder(root) {
if(!root){
return [];
}
var result = []
var stack = []
while( stack.length !== 0 || root ){
while(root){
stack.push(root);
root = root.left;
}
root = stack.pop();
result.push(root.element)
root = root.right;
}
return result;
}
后序遍历(不使用递归)
postorder(root) {
if(!root){
return [];
}
var result = []
var stack = [root]
while(stack.length!==0){
var top = stack.pop();
result.unshift(top.element);
if(top.left){
stack.push(top.left);
}
if(top.right){
stack.push(top.right);
}
}
return result;
}
最大深度
maxDepth(root) {
return !root ? 0 : Math.max(this.maxDepth(root.left), this.maxDepth(root.right)) + 1
}