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