Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // n - count of nodes in tree `s`,
- // m - count of nodes in tree `t`.
- // O(n * m) - time complexity,
- // O(n) - space complexity.
- class Solution {
- public boolean isSubtree(TreeNode s, TreeNode t) {
- return s != null && (isEquals(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t));
- }
- private boolean isEquals(TreeNode s, TreeNode t) {
- if (s == null && t == null) {
- return true;
- }
- if (s == null || t == null) {
- return false;
- }
- return s.val == t.val && isEquals(s.left, t.left) && isEquals(s.right, t.right);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement