二叉树的遍历
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}深度优先
前序遍历
中序遍历
后序遍历
广度优先遍历
最后更新于
function preOrder(root) {
if (!root) {
return;
}
// do something
// console.log(root.val)
preOrder(root.left);
preOrder(root.right);
}function preOrderWithoutRecursion(root) {
const stack = [];
let node = root;
while (node || stack.length > 0) {
if (node) {
// do something
// console.log(node.val);
stack.push(node);
node = node.left;
} else {
node = stack.pop().right;
}
}
}function inOrder(root) {
if (!root) {
return;
}
inOrder(root.left);
// do something
// console.log(root.val);
inOrder(root.right);
}function inOrderWithoutRecursion(root) {
const stack = [];
let node = root;
while (node || stack.length > 0) {
if (node) {
stack.push(node);
node = node.left;
} else {
const lastNode = stack.pop();
// do something
// console.log(lastNode.val);
node = lastNode.right;
}
}
}function postOrder(root) {
if (!root) {
return;
}
postOrder(root.left);
postOrder(root.right);
// do something
// console.log(root.val);
}function postOrderWithoutRecursion(root) {
if (!root) {
return;
}
const stack = [];
let node = root;
let last = node;
stack.push(node);
while (stack.length > 0) {
node = stack[stack.length - 1];
if (
(!node.left && !node.right) ||
(!node.right && last === node.left) ||
last === node.right
) {
// doing something
// console.log(node.val);
last = node;
stack.pop();
} else {
if (node.right) {
stack.push(node.right);
}
if (node.left) {
stack.push(node.left);
}
}
}
}function bfs(root) {
if (!root) {
return;
}
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
// do something
// console.log(node.val)
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
}