Print Common Nodes in Two Binary Search Trees
Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs.
from: http://www.geeksforgeeks.org/print-common-nodes-in-two-binary-search-trees/
Method 1 (Simple Solution) A simple way is to one by once search every node of first tree in second tree. Time complexity of this solution is O(m * h) where m is number of nodes in first tree and h is height of second tree.
Method 2 (Linear Time) We can find common elements in O(n) time.
1) Do inorder traversal of first tree and store the traversal in an auxiliary array ar1[].
2) Do inorder traversal of second tree and store the traversal in an auxiliary array ar2[]
3) Find intersection of ar1[] and ar2[]. See this for details.
Time complexity of this method is O(m+n) where m and n are number of nodes in first and second tree respectively. This solution requires O(m+n) extra space.
Method 3 (Linear Time and limited Extra Space) We can find common elements in O(n) time and O(h1 + h2) extra space where h1 and h2 are heights of first and second BSTs respectively.
The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs. Since we need to find common elements, whenever we get same element, we print it.
1 public List<Integer> commonNodes(TreeNode root1, TreeNode root2) { 2 List<Integer> list = new ArrayList<Integer>(); 3 4 Stack<TreeNode> stack1 = new Stack<TreeNode>(); 5 Stack<TreeNode> stack2 = new Stack<TreeNode>(); 6 7 while (root1 != null) { 8 stack1.push(root1); 9 root1 = root1.left; 10 } 11 12 while (root2 != null) { 13 stack2.push(root2); 14 root2 = root2.left; 15 } 16 17 while (stack1.size() > 0 && stack2.size() > 0) { 18 TreeNode node1 = stack1.peek(); 19 TreeNode node2 = stack2.peek(); 20 21 if (node1.val == node2.val) { 22 list.add(node1.val); 23 node1 = stack1.pop().right; 24 node2 = stack2.pop().right; 25 26 while (node1 != null) { 27 stack1.push(node1); 28 node1 = node1.left; 29 } 30 31 while (node2 != null) { 32 stack2.push(node2); 33 node2 = node2.left; 34 } 35 } else if (node1.val < node2.val) { 36 node1 = stack1.pop().right; 37 38 while (node1 != null) { 39 stack1.push(node1); 40 node1 = node1.left; 41 } 42 } else { 43 node2 = stack2.pop().right; 44 while (node2 != null) { 45 stack2.push(node2); 46 node2 = node2.left; 47 } 48 } 49 } 50 return list; 51 }