普通树:
const tree = {
val: 'a',
children: [
{
val: 'b',
children: [{val: 'd',children: []}, {val: 'e', hildren: []}],
},
{
val: 'c',
children: [{val: 'f', children: [],}, { val: 'g', children: [],}],
}
],
};
深度优先遍历
const dfs = (root) => {
console.log(root.val);
root.children.forEach(dfs);
}
广度优先遍历
cosnt bfs = (root) => {
const q = [root];
while(q.length > 0){
const n = q.shift();
console.log(n.val);
n.children.forEach(child = {
q.push(child);
});
}
}
二叉树
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null,
},
right: {
val: 5,
left: null,
right: null,
},
},
right: {
val: 3,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 7,
left: null,
right: null,
},
}
};
先序遍历
const preorder = (root) => {
if (!root) { return false; }
console.log(root.val);
preorder(root.left);
proorder(root.right);
}
// 1245367
先序遍历非迭代版本
const preorder = (root) => {
if (!root) {retrun false; }
const stack = [root];
while(stack.length) {
const n = stack.pop();
console.log(n.val);
if (n.right) { stack.push(right);}
if (n.left) { stack.push(left);}
}
}
// 1245367
中序遍历
const inorder = (root) => {
if (!root) { return false; }
inorder(root.left);
console.log(root.val);
inorder(root.right);
}
// 4251637
中序遍历非迭代版本
const inorder = (root) => {
if (!root) { return false; }
const stack = [];
let p = root;
while(stack.length || p) {
while(p) {
stack.push(p);
p = p.left;
}
const n = stack.pop();
console.log(n.val);
p = n.right;
}
}
// 4251637
后序遍历
const postorder = (root) => {
if (!root) { return false; }
postorder(root.left);
postorder(root.right);
console.log(root.value);
}
// 4526731
后序遍历非迭代版本
const postorder = (root) => {
if (!root) { return false; }
const outputStack = [];
const stack = [root];
while(stack.length) {
const n = stack.pop();
outputStack.push(n);
if (n.left) stack.push(n.left);
if (n.right) stack.push(n.right);
}
while(stack.length) {
const n = outputStack.pop();
console.log(n.val);
}
}
// 4526731