-
Notifications
You must be signed in to change notification settings - Fork 0
/
145.二叉树的后序遍历.js
99 lines (94 loc) · 1.64 KB
/
145.二叉树的后序遍历.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* @lc app=leetcode.cn id=145 lang=javascript
*
* [145] 二叉树的后序遍历
*
* https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
*
* algorithms
* Easy (75.89%)
* Likes: 880
* Dislikes: 0
* Total Accepted: 469.5K
* Total Submissions: 617.8K
* Testcase Example: '[1,null,2,3]'
*
* 给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
*
*
*
* 示例 1:
*
*
* 输入:root = [1,null,2,3]
* 输出:[3,2,1]
*
*
* 示例 2:
*
*
* 输入:root = []
* 输出:[]
*
*
* 示例 3:
*
*
* 输入:root = [1]
* 输出:[1]
*
*
*
*
* 提示:
*
*
* 树中节点的数目在范围 [0, 100] 内
* -100 <= Node.val <= 100
*
*
*
*
* 进阶:递归算法很简单,你可以通过迭代算法完成吗?
*
*/
// @lc code=start
/**
* 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 ans = []
const traverse = (root) => {
if (!root) return null
traverse(root.left)
traverse(root.right)
ans.push(root.val)
}
traverse(root)
return ans
}
// 迭代版本
var postorderTraversal = function (root) {
if (!root) return []
const ans = [],
stack = [root]
let cur
while (stack.length) {
cur = stack.pop()
ans.unshift(cur.val)
cur.left && stack.push(cur.left)
cur.right && stack.push(cur.right)
}
return ans
}
// @lc code=end