11. 二叉查找树中搜索区间
思路:稍稍改变中序遍历的逻辑
1 class Solution { 2 public: 3 /** 4 * @param root: param root: The root of the binary search tree 5 * @param k1: An integer 6 * @param k2: An integer 7 * @return: return: Return all keys that k1<=key<=k2 in ascending order 8 */ 9 void DFS(TreeNode *root, int k1, int k2, vector<int> &result) 10 { 11 if(root==0)return; 12 if(root->val>k2)DFS(root->left, k1, k2, result); 13 else if(root->val<k1)DFS(root->right, k1, k2, result); 14 else{ 15 DFS(root->left, k1, k2, result); 16 result.push_back(root->val);//中序遍历放中间 17 DFS(root->right, k1, k2, result); 18 } 19 } 20 vector<int> searchRange(TreeNode * root, int k1, int k2) { 21 vector<int> result; 22 DFS(root, k1, k2, result); 23 return result; 24 } 25 };