function traverse(tree) { if (!tree) return; let stack = [tree]; while (stack.length > 0) { let node = stack.pop(); console.log(node.val); if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); } }
function traverse(tree) { if (!tree) return; if (tree.left) traverse(tree.left); console.log(tree.val); if (tree.right) traverse(tree.right); }
非递归实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
function traverse(tree) { if (!tree) return; let stack = [tree]; while (stack.length > 0) { let top = stack[stack.length-1]; if (top.left) { stack.push(top.left); } else { while (stack.length > 0) { top = stack.pop(); console.log(top.val); if (top.right) { stack.push(top.right); break; } } } } }
post-order遍历
递归实现
1 2 3 4 5 6
function traverse(tree) { if (!tree) return; if (tree.left) traverse(tree.left); if (tree.right) traverse(tree.right); console.log(tree.val); }
非递归实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
function traverse(tree) { if (!tree) return; let stack = [tree]; let revStack = []; while (stack.length > 0) { let top = stack.pop(); revStack.push(top); if (top.left) stack.push(top.left); if (top.right) stack.push(top.right); }
while (revStack.length > 0) { let top = revStack.pop(); console.log(top.val); } }