Skip to main content

二叉树的后序遍历

Tips

题目类型: Tree

题目

手写二叉树的后序遍历.

示例

输入: TreeNode 实例

输出: 每个 TreeNode 节点的 val 组成的数组

题解

这没啥可说的了, 基本功.

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function (root) {
const res = []
if (root === null) return res

const stack1 = [root]
const stack2 = []

while (stack1.length !== 0) {
root = stack1.pop()

stack2.push(root)

if (root.left !== null) {
stack1.push(root.left)
}

if (root.right !== null) {
stack1.push(root.right)
}
}

while (stack2.length !== 0) {
const pop = stack2.pop()
res.push(pop.val)
}

return res
}