二叉树的前中后序遍历
var preOrder = function (root) {
const arr = [];
const order = (root) => {
if (!root) return;
arr.push(root.val);
order(root.left);
order(root.right);
};
order(root);
return arr;
};
var inOrder = function (root) {
const arr = [];
const order = (root) => {
if (!root) return;
order(root.left);
arr.push(root.val);
order(root.right);
};
order(root);
return arr;
};
var lastOrder = function (root) {
const arr = [];
const order = (root) => {
if (!root) return;
order(root.left);
order(root.right);
arr.push(root.val);
};
order(root);
return arr;
};
二叉树的层次遍历
var levelOrder=function(root){
if(!root) return [];
let queue=[root];
let res=[];
while(queue.length){
let temp=[];
let queueLength=queue.length;
while(queueLength){
let node=queue.unshift();
node.left&&queue.push(node.left)
node.right&&queue.push(node.right)
queueLength--;
temp.push(node.val)
}
res.push(temp)
}
return res;
}
深度优先遍历
function DFS(node,nodeList) {
if(node!=null){
nodeList.push(node)
let children=node.children;
for(let i=0;i<children.length;i++){
DFS(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;
}
广度优先遍历
function BFS(node) {
let nodes=[];
let stack=[];
if(node){
stack.push(node)
while(stack.length){
let item=stack.shift()
nodes.push(item)
let children=item.children;
for(let i=0;i<children.length;i++){
stack.push(children[i])
}
}
}
return nodes;
}
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;
}