|
| 1 | +package com.eprogrammerz.examples.algorithm.trees; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +import static org.junit.Assert.assertEquals; |
| 8 | + |
| 9 | +/** |
| 10 | + * Find longest path with unique node ids in given tree |
| 11 | + */ |
| 12 | +public class LongestUniquePath { |
| 13 | + /** |
| 14 | + * 6 |
| 15 | + * / \ |
| 16 | + * 3 7 |
| 17 | + * / \ \ |
| 18 | + * 2 5 6 |
| 19 | + * \ \ |
| 20 | + * 1 10 |
| 21 | + * \ |
| 22 | + * 7 |
| 23 | + * Unique path: [6,3,5,1] |
| 24 | + */ |
| 25 | + |
| 26 | + public int longestUniquePath(TreeNode root) { |
| 27 | + Set<Integer> path = new HashSet<>(); |
| 28 | + traversal(root, path, new ArrayList<>()); |
| 29 | + return path.size(); |
| 30 | + } |
| 31 | + |
| 32 | + private void traversal(TreeNode node, Set<Integer> path, ArrayList<Integer> temp) { |
| 33 | + if (node == null) return; |
| 34 | + // visit |
| 35 | + temp.add(node.val); |
| 36 | + |
| 37 | + if (node.left == null && node.right == null) { |
| 38 | + Set<Integer> result = new HashSet<>(temp); |
| 39 | + if (result.size() > path.size()) { |
| 40 | + path.clear(); |
| 41 | + path.addAll(result); |
| 42 | + temp.remove(temp.size() - 1); |
| 43 | + } |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + traversal(node.left, path, temp); |
| 48 | + traversal(node.right, path, temp); |
| 49 | + temp.remove(temp.size() - 1); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void testPathSum() { |
| 54 | + TreeNode root = new TreeNode(6); |
| 55 | + root.left = new TreeNode(3); |
| 56 | + root.right = new TreeNode(7); |
| 57 | + |
| 58 | + root.right.right = new TreeNode(6); |
| 59 | + |
| 60 | + root.left.left = new TreeNode(2); |
| 61 | + root.left.right = new TreeNode(5); |
| 62 | + root.left.right.right = new TreeNode(1); |
| 63 | + |
| 64 | + assertEquals(4, longestUniquePath(root)); |
| 65 | + |
| 66 | + // add right node to rightest node on last level |
| 67 | + root.right.right.right = new TreeNode(10); |
| 68 | + root.right.right.right.right = new TreeNode(7); |
| 69 | + |
| 70 | + assertEquals(4, longestUniquePath(root)); |
| 71 | + |
| 72 | + } |
| 73 | +} |
0 commit comments