• 문제 링크
Subtree of Another Tree - LeetCode
Can you solve this real interview question? Subtree of Another Tree - 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 and false otherwise. A subtree of a bin
leetcode.com
• 풀이 코드
public 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);
}
private boolean isSameTree(TreeNode a, TreeNode b) {
if (a == null && b == null) return true;
if (a == null || b == null || a.val != b.val) return false;
return isSameTree(a.left, b.left) && isSameTree(a.right, b.right);
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 589. N-ary Tree Preorder Traversal - Java (0) | 2026.09.06 |
|---|---|
| [LeetCode] 575. Distribute Candies - Java (0) | 2026.09.05 |
| [LeetCode] 566. Reshape the Matrix - Java (0) | 2026.09.03 |
| [LeetCode] 563. Binary Tree Tilt - Java (0) | 2026.09.02 |
| [LeetCode] 561. Array Partition - Java (0) | 2026.09.01 |
댓글