T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
First, we check if $t_2$ is null. If it is, then $t_2$ is definitely a subtree of $t_1$, so we return true.
Otherwise, we check if $t_1$ is null. If it is, then $t_2$ is definitely not a subtree of $t_1$, so we return false.
Next, we check if $t_1$ and $t_2$ are equal. If they are, then $t_2$ is a subtree of $t_1$, so we return true. Otherwise, we recursively check if $t_1$'s left subtree is equal to $t_2$, and if $t_1$'s right subtree is equal to $t_2$. If either is true, then $t_2$ is a subtree of $t_1$, so we return true.
The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in $t_1$.
1 2 3 4 5 6 7 8 9101112131415161718192021222324
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:defcheckSubTree(self,t1:TreeNode,t2:TreeNode)->bool:defdfs(t1,t2):ift2isNone:returnt1isNoneift1isNoneort1.val!=t2.val:returnFalsereturndfs(t1.left,t2.left)anddfs(t1.right,t2.right)ift2isNone:returnTrueift1isNone:returnFalseifdfs(t1,t2):returnTruereturnself.checkSubTree(t1.left,t2)orself.checkSubTree(t1.right,t2)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{publicbooleancheckSubTree(TreeNodet1,TreeNodet2){if(t2==null){returntrue;}if(t1==null){returnfalse;}if(dfs(t1,t2)){returntrue;}returncheckSubTree(t1.left,t2)||checkSubTree(t1.right,t2);}privatebooleandfs(TreeNodet1,TreeNodet2){if(t2==null){returnt1==null;}if(t1==null||t1.val!=t2.val){returnfalse;}returndfs(t1.left,t2.left)&&dfs(t1.right,t2.right);}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funccheckSubTree(t1*TreeNode,t2*TreeNode)bool{vardfsfunc(t1,t2*TreeNode)booldfs=func(t1,t2*TreeNode)bool{ift2==nil{returnt1==nil}ift1==nil||t1.Val!=t2.Val{returnfalse}returndfs(t1.Left,t2.Left)&&dfs(t1.Right,t2.Right)}ift2==nil{returntrue}ift1==nil{returnfalse}ifdfs(t1,t2){returntrue}returncheckSubTree(t1.Left,t2)||checkSubTree(t1.Right,t2)}