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 2Given tree t:
4 / 1 2Return 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 / 0Given tree t:
4 / 1 2Return false.
思路: 本质上还是树的遍历,考虑细节,递归中有递归。
/* 可以结合Leetcode 100 same tree 那道题来理解,这里要求是求一个树的子树是否包含另一个树,所以要遍历一遍第一个树(这里用先序遍历)。 所以递归函数中的函数也是递归函数,很有意思。 */ /** * 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 sameTree(TreeNode * s, TreeNode * t){ if (s == NULL && t == NULL){ return true; } if (s == NULL || t == NULL){ return false; } return s -> val == t -> val && sameTree(s -> left, t -> left) && sameTree(s -> right, t -> right); } bool isSubtree(TreeNode* s, TreeNode* t) { if (s == NULL){ // 若是第一个树到了末尾还没有找到则就是返回false return NULL; } if (sameTree(s , t)){ return true; } return isSubtree(s -> left, t) || isSubtree(s -> right, t); } };
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / \ / 2 1 1 2 [1,2,1], [1,1,2] Output: false
/** * 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 isSameTree(TreeNode* p, TreeNode* q) { if (p == NULL && q == NULL){ return true; } if (p == NULL || q == NULL){ return false; } return p -> val == q -> val && isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right); } };