Friday, March 9, 2018

11. Search Range in Binary Search Tree

Thinking:

  1. 简单的Traversal the tree
  2. 结果要求inorder 所以 left mid right

public class Solution {
    /**
     * @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
     */
    public List<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        helper(root, k1, k2, result);
        return result;
       
    }
    private void helper(TreeNode root, int k1, int k2,  List<Integer> result) {
        if (root == null) {
            return;
        }
       
       
        helper(root.left, k1, k2, result);
        if (root.val >= k1 && root.val <= k2) {
            result.add(root.val);
        }
       
        helper(root.right, k1, k2, result);
    }
}


No comments:

Post a Comment

4. Ugly Number

1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...