From d4b9ee095c3e4c43b41183f123469c50fb0c9c7e Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Tue, 4 Feb 2020 17:53:32 +0800 Subject: [PATCH] add 572 --- README.md | 1 + solutions/572. Subtree of Another Tree.md | 26 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 solutions/572. Subtree of Another Tree.md diff --git a/README.md b/README.md index db9b768..a87edaf 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 532 |[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/532.%20K-diff%20Pairs%20in%20an%20Array.md)|Easy| | | 561 |[Array Partition I](https://leetcode.com/problems/array-partition-i)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/561.%20Array%20Partition%20I.md)|Easy| | | 566 |[Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/566.%20Reshape%20the%20Matrix.md)|Easy| | +| 572 |[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[C++](solutions/572.%20Subtree%20of%20Another%20Tree.md)|Easy| | | 581 |[Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/581.%20Shortest%20Unsorted%20Continuous%20Subarray.md)|Easy| | | 605 |[Can Place Flowers](https://leetcode.com/problems/can-place-flowers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/605.%20Can%20Place%20Flowers.md)|Easy| | | 628 |[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/628.%20Maximum%20Product%20of%20Three%20Numbers.md)|Easy| | diff --git a/solutions/572. Subtree of Another Tree.md b/solutions/572. Subtree of Another Tree.md new file mode 100644 index 0000000..a1093f4 --- /dev/null +++ b/solutions/572. Subtree of Another Tree.md @@ -0,0 +1,26 @@ +# [572. Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) + +# 思路 +让我们求一个数是否是另一个树的子树,从题目中的第二个例子中可以看出,中间某个部分的不能算是子树。如果从s的某个结点开始,跟t的所有结构都一样就可以了,所以问题转换为判断两树是否相等,即[100. Same Tree](100.%20Same%20Tree.md)。 + + +# C++ + +``` C++ +class Solution { +private: + bool isSameTree(TreeNode* t1, TreeNode* t2){ + if(!t1 || !t2) return (!t1 && !t2); + return (t1 -> val == t2 -> val) && \ + isSameTree(t1 -> left, t2 -> left) && \ + isSameTree(t1 -> right, t2 -> right); + } +public: + bool isSubtree(TreeNode* s, TreeNode* t) { + if(!s) return t == NULL; + if(!t) return true; + return isSameTree(s, t) || isSubtree(s -> left, t) || isSubtree(s -> right, t); + } +}; +``` +