Given a binary search tree and a range
[k1, k2]
, return node values within a given range in ascending order.Example
Example 1:
Input:{5},6,10
Output:[]
5
it will be serialized {5}
No number between 6 and 10
Example 2:
Input:{20,8,22,4,12},10,22
Output:[12,20,22]
Explanation:
20
/ \
8 22
/ \
4 12
it will be serialized {20,8,22,4,12}
[12,20,22] between 10 and 22
Code (Java):
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ 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> ans = new ArrayList<>(); if (root == null) { return ans; } // stack stores all nodes greater or equal to k1 // Stack<TreeNode> stack = new Stack<>(); TreeNode p = root; while(p != null) { if (p.val >= k1) { stack.push(p); p = p.left; } else { p = p.right; } } while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (node.val <= k2) { ans.add(node.val); } findNext(node.right, stack); } return ans; } private void findNext(TreeNode p, Stack<TreeNode> stack) { while (p != null) { stack.push(p); p = p.left; } } }
No comments:
Post a Comment