LiteCode-Search Range in Binary Search Tree

Description

Given a binary search tree and a range [k1, k2], return all elements in the given range.

Example

If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].

    20
   /  \
  8   22
 / \
4   12
  • 题目模板

    /**
    * Definition of TreeNode:
    * class TreeNode {
    * public:
    *     int val;
    *     TreeNode *left, *right;
    *     TreeNode(int val) {
    *         this->val = val;
    *         this->left = this->right = NULL;
    *     }
    * }
    */
    
    class Solution {
    public:
      /**
       * @param root: param root: The root of the binary search tree
       * @param k1: An integer
       * @param k2: An integer
       * @return: return: Return all keys that k1<=key<=k2 in ascending order
       */
      vector<int> searchRange(TreeNode * root, int k1, int k2) {
          // write your code here
      }
    };
    
  • 题目大意

    给你一个二叉搜索树,和两个数k1,k2,让你输出在数中值介于这两个数的数。

  • 大概思路

    没啥好说的,遍历书吧,深搜广搜都可以。

    /**
    * Definition of TreeNode:
    * class TreeNode {
    * public:
    *     int val;
    *     TreeNode *left, *right;
    *     TreeNode(int val) {
    *         this->val = val;
    *         this->left = this->right = NULL;
    *     }
    * }
    */
    
    class Solution {
    public:
      /**
       * @param root: param root: The root of the binary search tree
       * @param k1: An integer
       * @param k2: An integer
       * @return: return: Return all keys that k1<=key<=k2 in ascending order
       */
      vector<int> searchRange(TreeNode * root, int k1, int k2) {
          // write your code here
          queue<TreeNode*> q;
          vector<int> v;
          if(!root)
            return v;
    
          q.push(root);
          while(!q.empty()){
            TreeNode *t = q.front();
            q.pop();
            if(t->val >= k1 && t->val <= k2)
              v.push_back(t->val);
            if(t->left)
              q.push(t->left);
            if(t->right)
              q.push(t->right);
          }
          return v;
      }
    };
    
  • 细节方面

    注意树可能为空直接返回空vector就可以了。

  • 题目链接: https://www.lintcode.com/problem/search-range-in-binary-search-tree/description

猜你喜欢

转载自blog.csdn.net/qq_24889575/article/details/81710679