Created
February 6, 2013 19:05
-
-
Save charlespunk/4724932 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1. | |
A tree T2 is a subtree if T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut of the tree at node n, the two trees would be identical. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static boolean containsTree(Node root, Node subtree){ | |
if(root == null) return false; | |
if(subtree == null) return true; | |
if(root.value == subTree.value && ckeckTree(root, subtree)) return true; | |
return (containsTree(root.left, subtree) || containsTree(root.right, subtree)); | |
} | |
public static boolean ckeckTree(Node root, Node subtree){ | |
if(root == null && subtree == null) return true; | |
else if(root == null || subtree == null) return false; | |
return (root.value == subtree.value && ckeckTree(root.left, subtree.left) && ckeckTree(root.right, subtree.right)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment