• LintCode题解之Search Range in Binary Search Tree


    1、题目描述

    2、问题分析

    首先将二叉查找树使用中序遍历的方式将元素放入一个vector,然后在vector 中截取符合条件的数字。

    3、代码

     1 /**
     2  * Definition of TreeNode:
     3  * class TreeNode {
     4  * public:
     5  *     int val;
     6  *     TreeNode *left, *right;
     7  *     TreeNode(int val) {
     8  *         this->val = val;
     9  *         this->left = this->right = NULL;
    10  *     }
    11  * }
    12  */
    13 
    14 class Solution {
    15 public:
    16     /**
    17      * @param root: param root: The root of the binary search tree
    18      * @param k1: An integer
    19      * @param k2: An integer
    20      * @return: return: Return all keys that k1<=key<=k2 in ascending order
    21      */
    22     vector<int> searchRange(TreeNode * root, int k1, int k2) {
    23         // write your code here
    24         vector<int> num ;
    25         inorder(num, root);
    26         
    27         
    28         
    29         vector<int> res;
    30         if( num.size() == 0)
    31             return res;
    32         int i = 0;
    33         int j = num.size() - 1;
    34         while( num[i] < k1) i++;
    35         while( num[j] > k2) j--;
    36         
    37         for(int k=  i; k <= j; k++){
    38             res.push_back(num[k]);
    39         }
    40         
    41         return res;
    42         
    43     }
    44     
    45     void  inorder(vector<int>& nums , TreeNode *root){
    46         if( root != NULL ){
    47             inorder(nums, root->left);
    48             nums.push_back(root->val);
    49             inorder(nums,root->right);
    50         }else {
    51             return ;
    52         }
    53             
    54         
    55       
    56     }
    57     
    58 };
    pp
  • 相关阅读:
    关于协同过滤技术
    一些数据上的概念
    Simple HBase query bridge
    leveraging
    Ajax.NET
    怎样实现给DEDE的栏目增加栏目图片(2)
    怎样实现给DEDE的栏目增加栏目图片(1)
    更改dede网站地图模板样式
    sublime如何实现函数折叠
    一步一步CCNA之五:交换机vlan配置
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/9571070.html
Copyright © 2020-2023  润新知