JavaScript实现二叉树的遍历
广度遍历
const res=new Array();
const stack=new Array(root);
let level=0
let bfs=()=>{
let node=stack[level];
if(node){
res.push(node.val);
if(node.left) stack.push(node.left)
if(node.right) stack.push(node.right)
level++
bfs()
}
}
前序遍历
const res=new Array();
let pfs=(root)=>{
if(root){
res.push(root.val);
pfs(root.left);
pfs(root.right);
}
}
中序遍历
const res=new Array();
let mfs=(root)=>{
if(root){
mfs(root.left);
res.push(root.val);
mfs(root.right);
}
}
后序遍历
const res=new Array();
let bfs=(root)=>{
if(root){
bfs(root.left);
bfs(root.right);
res.push(root.val);
}
}