leecode每日一題03-subtree of another tree
阿新 • • 發佈:2018-12-18
題目描述:
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 scould 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.
求解方法:
/** * 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 doesTree1hasTree2(TreeNode* tree1, TreeNode* tree2) { if(tree2 == NULL && tree1 == NULL) return true; if(tree2 == NULL || tree1 == NULL) return false; if(tree1->val == tree2->val) { return doesTree1hasTree2(tree1->left,tree2->left) && doesTree1hasTree2(tree1->right, tree2->right); } else { return false; } } bool isSubtree(TreeNode* s, TreeNode* t) { bool res = false; if(t == NULL) res = true; if(s == NULL) res = false; if(s && t) { if(s->val == t->val) res = doesTree1hasTree2(s,t); if(res == false) { res = isSubtree(s->left,t); } if(res == false) { res = isSubtree(s->right,t); } } return res; } };
小結:寫這種遞迴問題時,最關鍵的是要搞清楚終止條件,使其可以滿足不同情況,要不然很有可能在各種特殊case下出錯。