572. Subtree of Another Tree
Problem: 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的子树。
解决思路:依次遍历s的TreeNode,判断是不是跟t完全一样。
1 class Solution { 2 public: 3 bool isSame(TreeNode* s, TreeNode* t) { 4 if(s==nullptr && t==nullptr) 5 return true; 6 else if(s && t) { 7 if(s->val == t->val) 8 return (isSame(s->left, t->left) && isSame(s->right, t->right)); 9 return false; 10 } 11 else 12 return false; 13 } 14 bool isSubtree(TreeNode* s, TreeNode* t) { 15 if(s) { 16 if(isSame(s, t)) 17 return true; 18 return (isSubtree(s->left, t) || isSubtree(s->right, t)); 19 } 20 return false; 21 } 22 };