[LeetCode][572] Subtree of Another Tree題解
阿新 • • 發佈:2018-11-11
[LeetCode][572] Subtree of Another Tree題解
題意:給一個樹t和s,判斷在t中是否有一個子樹s。
思路:
dfs遍歷一個樹把t和s的val值一樣的節點加入treenode*型的vector中,再使用搜索判斷這個節點x開始,x和s是否一模一樣,這裡使用dfs來寫isSame
程式碼
/* * [572] Subtree of Another Tree * * https://leetcode.com/problems/subtree-of-another-tree/description/ * * algorithms * Easy (40.42%) * Total Accepted: 70.4K * Total Submissions: 174.1K * Testcase Example: '[3,4,5,1,2]\n[4,1,2]' * * * 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. * */ /** * 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 { private: vector<TreeNode *> res; public: bool isSubtree(TreeNode *s, TreeNode *t) { dfs(s, t); for (int i = 0; i < res.size(); i++) { if (isSame(t, res[i])) { return true; } } return false; } bool isSame(TreeNode *a, TreeNode *b) { if (a == nullptr && b == nullptr) { return true; } else if ((a == nullptr && b) || (a && b == nullptr)) { return false; } else if (a->val == b->val) { return isSame(a->left, b->left) && isSame(a->right, b->right); } return false; } void dfs(TreeNode *s, TreeNode *t) { if (s) { if (s->val == t->val) { res.push_back(s); } if (s->left) { dfs(s->left, t); } if (s->right) { dfs(s->right, t); } } } };
提交結果:
√ Accepted
√ 176/176 cases passed (16 ms)
√ Your runtime beats 56.2 % of cpp submissions