Problem
Given a binary tree, we need to find length of the longest consecutive sequence path where path refers to sequence of node in tree along with parent child connection.
Solutions
We can solve this in two parts, one will find out the root to leaf path and second will check the longest sequence in that path. Root to leaf can be found by traversing tree using pre-order traversal. This way we can find out the longest sequence in binary tree.
Solution below implements the approach.
import java.util.ArrayList; import java.util.List; public class LongestSeqInBT { private ListrootToLeafPath; private List longestSeq; public LongestSeqInBT(){ rootToLeafPath = new ArrayList<>(); longestSeq = new ArrayList<>(); } public void longestSeqInBTree(Node bTreeRoot, int index){ if (bTreeRoot != null){ if(rootToLeafPath.size() > index){ rootToLeafPath.set(index, bTreeRoot.data); } else rootToLeafPath.add(bTreeRoot.data); longestSeqInBTree(bTreeRoot.left, index + 1); longestSeqInBTree(bTreeRoot.right, index + 1); } else { LongestSeqInList(index); } } private void LongestSeqInList(int index) { if (index <= 0) return; Integer prev = Integer.MAX_VALUE; Integer maxSeqSize = 1; Integer currentSeqSize = 1; Integer startIndex = -1; Integer counter = 0; for (Integer i : rootToLeafPath){ counter++; if (i - 1 == prev){ currentSeqSize++; if (currentSeqSize > maxSeqSize){ maxSeqSize = currentSeqSize; startIndex = counter - currentSeqSize; } } else currentSeqSize = 1; prev = i; } if (maxSeqSize > longestSeq.size() && startIndex > -1){ longestSeq.clear(); for (int i = startIndex; i < startIndex + maxSeqSize ; i++) { longestSeq.add(rootToLeafPath.get(i)); } } } public static void main(String[] args) { LongestSeqInBT btSeq = new LongestSeqInBT(); Node node3 = new Node(3); Node node2 = new Node(2, node3, null); Node node7 = new Node(7); Node node6 = new Node(6, node7, null); Node node5 = new Node(5); Node node4 = new Node(4, node5, node6); Node bTree = new Node(1, node4, node2); Node.PrintInOrder(bTree); System.out.println(""); btSeq.longestSeqInBTree(bTree, 0); for (Integer i : btSeq.longestSeq){ System.out.print(i + " "); } } }
Comments are welcome. Question source geeksforgeeks
No comments:
Post a Comment