Created
May 16, 2019 15:58
-
-
Save shixiaoyu/67d197df03174225df58a88e143d0f18 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public List<Integer> closestKValuesUsingPreOrder(TreeNode root, double target, int k) { | |
List<Integer> res = new ArrayList<>(); | |
// PQ by default is ascending order using the element's natural order, so by default, it's a min heap | |
Queue<Node> pq = new PriorityQueue<>(); // max heap | |
this.preOrderTraversal(root, target, pq, k); | |
for (Node n : pq) { | |
res.add(n.val); | |
} | |
return res; | |
} | |
// This method uses a pre-order traversal that traverses the entire tree, O(N*lgK), not optimal | |
public void preOrderTraversal(TreeNode root, double target, Queue<Node> pq, int k) { | |
if (root == null) { | |
return; | |
} | |
if (pq.size() < k) { | |
pq.add(new Node(root.val, Math.abs(target - root.val))); | |
} else { | |
double diff = Math.abs(target - root.val); | |
if (diff < pq.peek().diff) { | |
pq.poll(); | |
pq.add(new Node(root.val, diff)); | |
} | |
} | |
this.preOrderTraversal(root.left, target, pq, k); | |
this.preOrderTraversal(root.right, target, pq, k); | |
} | |
public class Node implements Comparable { | |
public int val; | |
public double diff; | |
public Node(int val, double diff) { | |
this.val = val; | |
this.diff = diff; | |
} | |
// Want to build a max heap | |
public int compareTo(Object o) { | |
Node n = (Node)o; | |
return (int)(n.diff - this.diff); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment