Lintcode: Search Range in Binary Search Tree, lintcodebinary

Source: Internet
Author: User

Lintcode: Search Range in Binary Search Tree, lintcodebinary

Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order.ExampleFor example, if k1 = 10 and k2 = 22, then your function should print 12, 20 and 22.          20       /        \    8           22  /     \4       12

My approach is to deform inorder traversal and determine whether to apply recursion to the left to determine whether it is root. val> k1. If no, the left recursion is not required. The processing method of the right subtree is similar.

 1 public class Solution { 2     /** 3      * @param root: The root of the binary search tree. 4      * @param k1 and k2: range k1 to k2. 5      * @return: Return all keys that k1<=key<=k2 in ascending order. 6      */ 7     public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { 8         ArrayList<Integer> res = searchRangeRecur(root,k1,k2); 9         return res;10     }11 12     public ArrayList<Integer> searchRangeRecur(TreeNode cur, int k1, int k2){13         ArrayList<Integer> res = new ArrayList<Integer>();14         if (cur==null) return res;15         if (k1>k2) return res;16 17         ArrayList<Integer> left = searchRangeRecur(cur.left,k1,Math.min(cur.val-1,k2));18         ArrayList<Integer> right = searchRangeRecur(cur.right,Math.max(cur.val+1,k1),k2);19 20         res.addAll(left);21         if (cur.val>=k1 && cur.val<=k2) res.add(cur.val);22         res.addAll(right);23 24         return res;25     }26         27 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.