572. Subtree of Another Tree
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.
解法一:思路:利用二叉树的遍历求解,如中序遍历,如果序列化后得到的字符串t为字符串s的子串,则t为s的子树。需要注意是要将空节点也序列化成一个字符。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
return serialize(s).contains(serialize(t));
}
private String serialize(TreeNode root){
StringBuilder sb = new StringBuilder();
serialize(root,sb);
return sb.toString();
}
private void serialize(TreeNode root,StringBuilder sb){
if(root==null){
sb.append("#");
return;
}
sb.append(",").append(root.val);
serialize(root.left,sb);
serialize(root.right,sb);
}
}
解法二:辅助函数 areIdentical()用来判断两个二叉树是否为同一颗二叉树,原问题中,如果二叉树s和t为同一颗树,则必为子树,否则就继续递归判断t是否为左子树或者右子树的子树:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(t==NULL)
return true;
if(s==NULL)
return false;
if(areIdentical(s,t))
return true;
return isSubtree(s->left,t)||isSubtree(s->right,t);
}
private: bool areIdentical(TreeNode* root1, TreeNode* root2){
if(root1==NULL&&root2==NULL)
return true;
if(root1==NULL||root2==NULL)
return false;
if(root1->val!=root2->val)
return false;
return areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right);
}
};