145. Binary Tree Postorder Traversal - Easy
문제
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
제한사항
- The number of the nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
입출력 예
1
2
3
4
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
1
2
3
4
Example 2:
Input: root = []
Output: []
1
2
3
4
Example 3:
Input: root = [1]
Output: [1]
1
2
3
4
5
Example 4:
Input: root = [1,2]
Output: [2,1]
1
2
3
4
5
Example 5:
Input: root = [1,null,2]
Output: [2,1]
풀이
- Tree
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if (!root) {
return {};
}
vector<int> res;
vector<int> left = postorderTraversal(root->left);
if (!left.empty()) {
res.insert(res.end(), left.begin(), left.end());
}
vector<int> right = postorderTraversal(root->right);
if (!right.empty()) {
res.insert(res.end(), right.begin(), right.end());
}
res.push_back(root->val);
return res;
}
};