Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
思路:首先构造一个isSame method,应该可以,没难度,那么剩下的就是遍历,找到root相同,进行判断就可以了;O(N)
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root == null) {
return false;
}
if(root.val == subRoot.val) {
if(isSameTree(root, subRoot)) {
return true;
}
}
if(isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)) {
return true;
}
return false;
}
private boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) {
return true;
}
if(p == null || q == null) {
return false;
}
if(p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
如果tree很大,dfs会stack overflow,那么采用queue,level order来判断,用heap来做memory,可以避免这个问题;
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root == null) {
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(node.val == subRoot.val) {
if(isSameTree(node, subRoot)) {
return true;
}
}
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return false;
}
private boolean isSameTree(TreeNode node1, TreeNode node2) {
if(node1 == null && node2 == null) {
return true;
}
if(node1 == null || node2 == null) {
return false;
}
if(node1.val != node2.val) {
return false;
}
return isSameTree(node1.left, node2.left) && isSameTree(node1.right, node2.right);
}
}