描述
给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
您在真实的面试中是否遇到过这个题?
是
样例
如果有 k1 = 10
和 k2 = 22
, 你的程序应该返回 [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
vector<int> m_res;
search(root,k1,k2,m_res);
return m_res;
}
void search(TreeNode *root,int k1,int k2,vector<int>&res){
if(root==NULL) return;
if(root->val<=k2&&root->val>=k1){
search(root->left,k1,k2,res);
res.push_back(root->val);
search(root->right,k1,k2,res);
}
else if(root->val>k2) search(root->left,k1,k2,res);
else search(root->right,k1,k2,res);
}
};
注意:类中.和-> 的区别