LeetCode-145. Binary Tree Postorder Traversal

问题描述

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Constraints:

  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

解答

方法一:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @Description: 145. Binary Tree Postorder Traversal
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 递归写法一
* @param {TreeNode} root
* @return {number[]}
*/
const postorderTraversal = function (root) {
if (!root) {
return []
}

return [...postorderTraversal(root.left), ...postorderTraversal(root.right), root.val]
}
/**
* @description: 递归写法二
* @param {TreeNode} root
* @return {number[]}
*/
const postorderTraversal = function (root) {
let res = []
const visitLoop = (root) => {
if (root) {
visitLoop(root.left)
visitLoop(root.right)
res.push(root.val)
}
}
visitLoop(root)
return res
}
方法二:迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @Description: 145. Binary Tree Postorder Traversal
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: 迭代
* @param {TreeNode} root
* @return {number[]}
*/
const postorderTraversal = function (root) {
let stack = []
let res = []
let cur = root
let flag = cur

while (cur || stack.length) {
if (cur) {
stack.push(cur)
cur = cur.left
} else {
cur = stack[stack.length - 1]
if (cur.right && cur.right !== flag) {
cur = cur.right
} else {
cur = stack.pop()
res.push(cur.val)
flag = cur
cur = null
}
}
}
return res
}