vault backup: 2022-07-07 08:37:25
This commit is contained in:
parent
ceb36abb66
commit
7da47010dd
|
@ -63,6 +63,10 @@ Output: []
|
|||
> [!summary]
|
||||
> This is a #DFS or #BFS problem. We search values in the tree.
|
||||
|
||||
In DFS, I use preorder, since the root value will be check first, making it quicker if data appear on shallow trees more.
|
||||
|
||||
In BFS, I don't have use for loop inside while loop, since we don't have to consider levels.
|
||||
|
||||
### Solution
|
||||
|
||||
DFS
|
||||
|
@ -142,5 +146,41 @@ public:
|
|||
|
||||
BFS
|
||||
```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:
|
||||
TreeNode *searchBST(TreeNode *root, int val) {
|
||||
// BFS
|
||||
queue<TreeNode *> pending;
|
||||
pending.push(root);
|
||||
|
||||
TreeNode *ptr;
|
||||
while (!pending.empty()) {
|
||||
ptr = pending.front();
|
||||
pending.pop();
|
||||
|
||||
if (ptr->val == val) {
|
||||
return ptr;
|
||||
}
|
||||
|
||||
if (ptr->left)
|
||||
pending.push(ptr->left);
|
||||
if (ptr->right)
|
||||
pending.push(ptr->right);
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue