|
1 | 1 | package com.inuker.test;
|
2 | 2 |
|
3 | 3 | import com.inuker.solution.BinaryTreeInorderTraversal;
|
| 4 | +import com.inuker.solution.ClosestBinarySearchTreeValueII; |
4 | 5 | import com.inuker.solution.InorderSuccessorInBST;
|
5 | 6 | import com.leetcode.library.TreeNode;
|
6 | 7 |
|
| 8 | +import java.util.LinkedList; |
7 | 9 | import java.util.List;
|
| 10 | +import java.util.Stack; |
8 | 11 |
|
9 | 12 | public class main {
|
10 | 13 |
|
11 | 14 | public static void main(String[] args) {
|
12 | 15 | TreeNode root = TreeNode.buildTree(new Integer[]{
|
13 |
| - 20, 10, 40, 5, 15, 30, 60, 2, 7, 12, 18, 25, 35, 50, 70 |
| 16 | + 2, 1 |
14 | 17 | });
|
15 | 18 |
|
16 |
| - List<TreeNode> list = new InorderSuccessorInBST().getAllPredesessor(root, 40); |
17 |
| - for (TreeNode n : list) { |
18 |
| - System.out.print(n.val + " "); |
| 19 | + List<Integer> list = closestKValues(root, 4.14, 2); |
| 20 | + for (Integer n : list) { |
| 21 | + System.out.print(n + " "); |
19 | 22 | }
|
20 | 23 | }
|
21 | 24 |
|
| 25 | + public static List<Integer> closestKValues(TreeNode root, double target, int k) { |
| 26 | + Stack<TreeNode> preStack = new Stack<>(); |
| 27 | + Stack<TreeNode> postStack = new Stack<>(); |
| 28 | + |
| 29 | + for (TreeNode node = root; node != null; ) { |
| 30 | + if (target <= node.val) { |
| 31 | + postStack.push(node); |
| 32 | + node = node.left; |
| 33 | + } else { |
| 34 | + preStack.push(node); |
| 35 | + node = node.right; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + List<Integer> list = new LinkedList<>(); |
| 40 | + |
| 41 | + for (int i = 0; i < k; i++) { |
| 42 | + if (preStack.isEmpty()) { |
| 43 | + list.add(getNextSuccessor(postStack).val); |
| 44 | + } else if (postStack.isEmpty()) { |
| 45 | + list.add(getNextPredesessor(preStack).val); |
| 46 | + } else if (Math.abs(target - preStack.peek().val) < Math.abs(target - postStack.peek().val)) { |
| 47 | + list.add(getNextPredesessor(preStack).val); |
| 48 | + } else { |
| 49 | + list.add(getNextSuccessor(postStack).val); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return list; |
| 54 | + } |
| 55 | + |
| 56 | + private static TreeNode getNextPredesessor(Stack<TreeNode> stack) { |
| 57 | + if (stack.isEmpty()) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + TreeNode ret = stack.pop(); |
| 61 | + for (TreeNode node = ret.left; node != null; node = node.right) { |
| 62 | + stack.push(node); |
| 63 | + } |
| 64 | + return ret; |
| 65 | + } |
| 66 | + |
| 67 | + private static TreeNode getNextSuccessor(Stack<TreeNode> stack) { |
| 68 | + if (stack.isEmpty()) { |
| 69 | + return null; |
| 70 | + } |
| 71 | + TreeNode ret = stack.pop(); |
| 72 | + for (TreeNode node = ret.right; node != null; node = node.left) { |
| 73 | + stack.push(node); |
| 74 | + } |
| 75 | + return ret; |
| 76 | + } |
22 | 77 | }
|
0 commit comments