notes/OJ notes/pages/Leetcode Binary-Tree-Postorder-Traversal.md

104 lines
1.8 KiB
Markdown
Raw Normal View History

2022-07-05 09:08:49 +08:00
# Leetcode Binary-Tree-Postorder-Traversal
#### 2022-07-04 21:31
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
> #algorithm #DFS #DFS_postorder
>
2022-07-05 09:08:49 +08:00
> ##### Data structures:
2022-09-03 15:41:36 +08:00
>
> #DS #binary_tree
>
2022-07-05 09:08:49 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-07-05 09:08:49 +08:00
> #coding_problem #difficulty-
2022-09-03 15:41:36 +08:00
>
2022-07-05 09:08:49 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode #CS_list_need_practicing
>
2022-07-05 09:08:49 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-05 09:08:49 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
- [Link to problem](https://leetcode.com/problems/binary-tree-postorder-traversal/)
2022-09-03 15:41:36 +08:00
---
2022-07-05 09:08:49 +08:00
### Problem
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
https://leetcode.com/problems/binary-tree-postorder-traversal/
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
#### Examples
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
**Example 1:**
![](https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg)
**Input:** root = [1,null,2,3]
**Output:** [3,2,1]
**Example 2:**
**Input:** root = []
**Output:** []
**Example 3:**
**Input:** root = [1]
**Output:** [1]
#### Constraints
2022-09-03 15:41:36 +08:00
- The number of the nodes in the tree is in the range `[0, 100]`.
- `-100 <= Node.val <= 100`
2022-07-05 09:08:49 +08:00
### Thoughts
Same as [[Leetcode Binary-Tree-Inorder-Traversal]] and [[Leetcode Binary-Tree-Preorder-Traversal]]
== TODO: write iteration and another algo #TODO ==
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
### Solution
Recursion
2022-09-03 15:41:36 +08:00
2022-07-05 09:08:49 +08:00
```cpp
/**
* 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 {
void postorder(TreeNode *root, vector<int> &answer) {
if (root == nullptr) {
return;
}
postorder(root->left, answer);
postorder(root->right, answer);
answer.push_back(root->val);
}
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> answer;
postorder(root, answer);
return answer;
}
};
2022-09-03 15:41:36 +08:00
```