diff --git a/CS notes/pages/Leetcode Search-In-a-Binary-Tree.md b/CS notes/pages/Leetcode Search-In-a-Binary-Tree.md index 0291592..dee1e15 100644 --- a/CS notes/pages/Leetcode Search-In-a-Binary-Tree.md +++ b/CS notes/pages/Leetcode Search-In-a-Binary-Tree.md @@ -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 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; + } +}; ``` \ No newline at end of file