vault backup: 2022-07-04 15:32:45

This commit is contained in:
juan 2022-07-04 15:32:45 +08:00
parent 7362c55585
commit 2149af6483

View file

@ -59,7 +59,52 @@ Preorder, means root is at the "Pre" position, so the order is:
The recursion version is easy to implement. The recursion version is easy to implement.
Use Stacks for the iteration method, because stacks are FILO, the **subtree will get traversed first.**
And remember to push **right subtree** first, so that the left one will be traversed first.
### Solution ### Solution
Iteration
```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 {
public:
vector<int> preorderTraversal(TreeNode *root) {
if (!root) {
return {};
}
// Using stacks, since FILO, the latest gets served first.
vector<int> answer;
stack<TreeNode *> pending;
do {
if (root != nullptr) {
answer.push_back(root->val);
// nothing gets pushed if is nullptr;
pending.push(root->right);
pending.push(root->left);
}
root = pending.top();
pending.pop();
} while (root || !pending.empty());
return answer;
}
};
```
Recursion, using private funcs: Recursion, using private funcs:
```cpp ```cpp
/** /**