给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
/**
* 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) {
// for null node, return empty vector
vector<int> res;
// return empty vector
if (root == NULL) {
return res;
}
// stack to support mid-order visit
stack<TreeNode *> st;
while (root != NULL || !st.empty()) {
while (root != NULL) {
st.push(root);
root = root->left;
}
TreeNode * node = st.top();
st.pop();
if (node->val <= k2 && node->val >= k1) {
res.push_back(node->val);
}
root = node->right;
}
return res;
}
};
recursive:
/**
* 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) {
// for null node, return empty vector
vector<int> res;
// return empty vector
if (root == NULL) {
return res;
}
// recurseve
midOrderVisit(root, k1, k2, res);
return res;
}
void midOrderVisit(TreeNode* root, int k1, int k2, vector<int> & res) {
if (root == NULL) {
return;
}
// visit left children
midOrderVisit(root->left, k1, k2, res);
// visit root
if (root->val <= k2 && root->val >= k1) {
res.push_back(root->val);
}
// visit right children
midOrderVisit(root->right, k1, k2, res);
}
};