vault backup: 2022-07-04 15:08:23
This commit is contained in:
parent
5009118bee
commit
7362c55585
|
@ -56,9 +56,45 @@ Preorder, means root is at the "Pre" position, so the order is:
|
|||
- Search root node
|
||||
- Search left sub-tree
|
||||
- Search right sub-tree
|
||||
|
||||
The recursion version is easy to implement.
|
||||
|
||||
### Solution
|
||||
Recursion, using private funcs:
|
||||
```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) {
|
||||
// Use two functions:
|
||||
vector<int> answer;
|
||||
preorder(root, answer);
|
||||
return answer;
|
||||
}
|
||||
|
||||
private:
|
||||
void preorder(TreeNode *root, vector<int> &answer) {
|
||||
if (root == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
answer.push_back(root->val);
|
||||
preorder(root->left, answer);
|
||||
preorder(root->right, answer);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Recursion:
|
||||
```cpp
|
||||
|
@ -96,4 +132,4 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
```
|
||||
```
|
||||
|
|
Loading…
Reference in a new issue