树结构及测试用例
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val);
this.left = (left===undefined ? null : left);
this.right = (right===undefined ? null : right);
}
const testCase = new TreeNode(
1,
new TreeNode(2, new TreeNode(4), new TreeNode(5, new TreeNode(7))),
new TreeNode(3, undefined, new TreeNode(6, new TreeNode(8), new TreeNode(9)))
)
graph TB
1---2
1---3
2---4
2---5
5--left---7
3--right---6
6---8
6---9
递归
function traversal1(root) {
return root ? (
[root.val, ...traversal(root.left), ...traversal(root.right)]
) : [];
}
function traversal2(root) {
const result = [];
function findNode(node) {
if (!node) return;
result.push(node.val);
findNode(node.left);
findNode(node.right);
}
findNode(root);
return result;
}
迭代
前序/中序
function traversal(root) {
const result = [];
const stack = [];
while (stack.length || root) {
while (root) {
result.push(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return result;
}
后序
function postorderTraversal1(root) {
const result = [];
const stack = [];
while (stack.length || root) {
while (root) {
result.unshift(root.val);
stack.push(root);
root = root.right;
}
root = stack.pop();
root = root.left;
}
return result;
}
function postorderTraversal2(root) {
const result = [];
const stack = [];
let visited;
while (stack.length || root) {
while (root) {
stack.push(root);
root = root.left;
}
root = stack[stack.length - 1];
if (!root.right || (root.right === visited)) {
root = stack.pop();
result.push(root.val);
visited = root;
root = null;
} else {
root = root.right;
}
}
return result;
}
function postorderTraversal3(root) {
const result = [];
const stack = [root];
while (stack.length) {
root = stack.pop();
if (root) {
stack.push(root, null);
if (root.right) stack.push(root.right);
if (root.left) stack.push(root.left);
} else {
root = stack.pop();
result.push(root.val);
}
}
return result;
}
Morris
前序/中序
function traversal(root) {
const result = [];
let predecessor;
while (root) {
if (root.left) {
predecessor = root.left;
while (predecessor.right && (predecessor.right !== root)) {
predecessor = predecessor.right;
}
if (!predecessor.right) {
predecessor.right = root;
result.push(root.val);
root = root.left;
} else {
predecessor.right = null;
root = root.right;
}
} else {
result.push(root.val);
root = root.right;
}
}
return result;
};
后序
function traversel(root) {
const result = [];
let predecessor;
while (root) {
if (root.right) {
predecessor = root.right;
while (predecessor.left && (predecessor.left !== root)) {
predecessor = predecessor.left;
}
if (!predecessor.left) {
predecessor.left = root;
result.unshift(root.val);
root = root.right;
} else {
predecessor.left = null;
root = root.left;
}
} else {
result.unshift(root.val);
root = root.left;
}
}
return result;
}