Skip to content

[minji-go] week 15 solutions #1657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions subtree-of-another-tree/minji-go.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* <a href="https://leetcode.com/problems/subtree-of-another-tree/">week15-1. subtree-of-another-tree</a>
* <li>Description: Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot </li>
* <li>Topics: Tree, Depth-First Search, String Matching, Binary Tree, Hash Function</li>
* <li>Time Complexity: O(N*M), Runtime 2ms </li>
* <li>Space Complexity: O(H), Memory 43.98MB </li>
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}

public boolean isSameTree(TreeNode root, TreeNode subRoot) {
if (root == null && subRoot == null) return true;
if (root == null || subRoot == null) return false;
if (root.val != subRoot.val) return false;
return isSameTree(root.left, subRoot.left) && isSameTree(root.right, subRoot.right);
}
}