Advertisement
Guest User

Closest Leaf

a guest
Apr 21st, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. My solution is simple:
  2.  
  3. First, preform DFS on root in order to find the node whose val = k, at the meantime use HashMap to keep record of all back edges from child to parent;
  4. Then perform BFS on this node to find the closest leaf node.
  5. class Solution {
  6.  
  7. public int findClosestLeaf(TreeNode root, int k) {
  8. Map<TreeNode, TreeNode> backMap = new HashMap<>(); // store all edges that trace node back to its parent
  9. Queue<TreeNode> queue = new LinkedList<>(); // the queue used in BFS
  10. Set<TreeNode> visited = new HashSet<>(); // store all visited nodes
  11.  
  12. // DFS: search for node whoes val == k
  13. TreeNode kNode = DFS(root, k, backMap);
  14. queue.add(kNode);
  15. visited.add(kNode);
  16.  
  17. // BFS: find the shortest path
  18. while(!queue.isEmpty()) {
  19. TreeNode curr = queue.poll();
  20. if(curr.left == null && curr.right == null) {
  21. return curr.val;
  22. }
  23. if(curr.left != null && visited.add(curr.left)) {
  24. queue.add(curr.left);
  25. }
  26. if(curr.right != null && visited.add(curr.right)) {
  27. queue.add(curr.right);
  28. }
  29. if(backMap.containsKey(curr) && visited.add(backMap.get(curr))) { // go alone the back edge
  30. queue.add(backMap.get(curr));
  31. }
  32. }
  33. return -1; // never hit
  34. }
  35.  
  36. private TreeNode DFS(TreeNode root, int k, Map<TreeNode, TreeNode> backMap) {
  37. if(root.val == k) {
  38. return root;
  39. }
  40. if(root.left != null) {
  41. backMap.put(root.left, root); // add back edge
  42. TreeNode left = DFS(root.left, k, backMap);
  43. if(left != null) return left;
  44. }
  45. if(root.right != null) {
  46. backMap.put(root.right, root); // add back edge
  47. TreeNode right = DFS(root.right, k, backMap);
  48. if(right != null) return right;
  49. }
  50. return null;
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement