写法很多,这里只写一种。
使用栈先序遍历二叉树。144. Binary Tree Preorder Traversal .
var preorderTraversal = function(root) {
if (!root) return []
const res = []
const stack = [root]
while (stack.length) {
root = stack.pop()
res.push(root.val)
if (root.right) stack.push(root.right)
if (root.left) stack.push(root.left)
}
return res
};
使用栈中序遍历二叉树。94. Binary Tree Inorder Traversal .
var inorderTraversal = function(root) {
const res = []
const stack = []
while (root) {
stack.push(root)
root = root.left
}
while (stack.length) {
root = stack.pop()
res.push(root.val)
root = root.right
while (root) {
stack.push(root)
root = root.left
}
}
return res
};
使用栈后序遍历二叉树.145. Binary Tree Postorder Traversal .
var postorderTraversal = function(root) {
if (!root) return []
const res = []
const stack = [root]
while (stack.length) {
const root = stack[stack.length-1]
if (root.right||root.left) {
// 设成null是为了防止无限循环
if (root.right) {
stack.push(root.right)
root.right = null
}
if (root.left) {
stack.push(root.left)
root.left = null
}
} else res.push((stack.pop()).val)
}
return res
};
// 后序遍历的第二种方法:不改变结点内容
var postorderTraversal = function(root) {
if (!root) return []
const res = []
const stack = [root]
while (stack.length) {
root = stack.pop()
res.unshift(root.val)
if (root.left) stack.push(root.left)
if (root.right) stack.push(root.right)
}
return res
};