Search Range in Binary Search Tree

Search Range in Binary Search Tree.png

解題思路 :

recursive 作業(yè)順序:

  1. 往左檢查 left child 只要有符合 > k1 的 node 就繼續(xù)往左找更小的可能符合要求的點(diǎn)
  2. 檢查當(dāng)前的點(diǎn) 如果數(shù)值 x 符合 k1 <= x <= k2 就放入 result
  3. 向右檢查 right child 只要符合 < k2 的 node 就繼續(xù)往右找更大的可能符合要求的點(diǎn)

C++ code :

<pre><code>
class Solution {

public:

/**
 * @param root: The root of the binary search tree.
 * @param k1 and k2: range k1 to k2.
 * @return: Return all keys that k1<=key<=k2 in ascending order.
 */
void findRange(TreeNode *root, int k1, int k2, vector<int> &res){
    if(root->left && root->val > k1) findRange(root->left, k1, k2, res);
    if(root->val >= k1 && root->val <= k2) res.emplace_back(root->val);
    if(root->right && root->val < k2) findRange(root->right, k1, k2, res);
}
 
vector<int> searchRange(TreeNode* root, int k1, int k2) {
    // write your code here
    vector<int> res;
    if(root != nullptr) findRange(root, k1, k2, res);
    return res;
}

};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容