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.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
思路:题目要求的是t树是属于s树的包含叶子节点的树,故第二个例子中s树多了一个0,故而不满足。
根据这个条件,我们可以清楚的知道。t树要是s树的子树,那么满足的条件有:
1.t->val == s->val 首先当然当前节点的数值要相等
2.t->left = s->left
3.t->right = s->right 左右子树也必须递归的相等。
代码:
bool helper(TreeNode* s, TreeNode* t) {