二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
输入: [1,null,2,3]
1
\
2
/
3输出: [3,2,1]
递归法
/**
* 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 = [];
const inorder = function (root) {
if (root === null) return;
inorder(root.left)
inorder(root.right)
res.push(root.val)
}
inorder(root)
return res;
};
栈
/**
* 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 = [], stack = [];
if (root === null) return res
while (stack.length || root !== null) {
if (root !== null) {
stack.push(root);
res.unshift(root.val);
root = root.right;
} else {
root = stack.pop();
root = root.left;
}
}
return res;
};