1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| class Solution { public int findClosestLeaf(TreeNode root, int k) { Map<TreeNode, Integer> map = new HashMap<>(); getDistance(root, map, 0); TreeNode node = findNode(root, k); int res = Integer.MAX_VALUE, minDist = Integer.MAX_VALUE; for (TreeNode cur : map.keySet()) { if (cur.left == null && cur.right == null) { TreeNode lca = lowestCommonAncestor(root, node, cur); int curDist = map.get(node) + map.get(cur) - 2 * map.get(lca); if (curDist < minDist) { minDist = curDist; res = cur.val; } } } return res; } private void getDistance(TreeNode root, Map<TreeNode, Integer> map, int dist) { if (root == null) { return; } map.put(root, dist); getDistance(root.left, map, dist + 1); getDistance(root.right, map, dist + 1); } private TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } if (root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } return left == null ? right : left; } private TreeNode findNode(TreeNode root, int k) { if (root.val == k) { return root; } if (root.left != null) { TreeNode left = findNode(root.left, k); if (left != null) { return left; } } if (root.right != null) { TreeNode right = findNode(root.right, k); if (right != null) { return right; } } return null; } }
|