http://www.lintcode.com/en/problem/subtree/
- have a helper function to identify whether the two are identical. and divide and conquer on the large tree until there is a match of T1. currentNode.val = T2.root.val and call the helper function
- since it is sub tree that means all the way to the leaf node on both.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
public boolean isSubtree(TreeNode T1, TreeNode T2) {
// write your code here
if (T1 == null && T2 == null) {
return true;
}
if (T2 == null) {
return true;
}
if (T1 == null) {
return false;
}
if (T1.val == T2.val) {
if (isIdentical(T1, T2)) {
return true;
}
}
boolean left = isSubtree(T1.left, T2);
boolean right = isSubtree(T1.right, T2);
return left || right;
}
public boolean isIdentical(TreeNode T1, TreeNode T2) {
if (T1 == null && T2 == null) {
return true;
}
if (T1 == null || T2 == null) {
return false;
}
boolean left = isIdentical(T1.left, T2.left);
boolean right = isIdentical(T1.right, T2.right);
return T1.val == T2.val && left && right;
}
}
- traverse method
public class Solution {
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
public boolean isSubtree(TreeNode T1, TreeNode T2) {
// write your code here
if (T2 == null) {
return true;
}
if (T1 == null) {
return false;
}
if (T1.val == T2.val && isIdentical(T1, T2)) {
return true;
}
if (isSubtree(T1.left, T2) || isSubtree(T1.right, T2)) {
return true;
}
return false;
}
public boolean isIdentical(TreeNode T1, TreeNode T2) {
if (T1 == null && T2 == null) {
return true;
}
if (T1 == null || T2 == null) {
return false;
}
return T1.val == T2.val && isIdentical(T1.left, T2.left) && isIdentical(T1.right, T2.right);
}
}