Leetcode 572. Subtree of Another Tree
Given the roots of two binary trees root and subRoot, determine if there is a subtree of root with the same structure and node values of subRoot. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node’s descendants. The tree tree could also be considered as a subtree of itself.
root and subRoot be null?
true.subRoot is null but root is not, what should the output be?
subRoot is null, it should always return true regardless of root.root is null but subRoot is not, what should the output be?
root is null but subRoot is not, it should return false.isSameTree to check if two trees are identical.root).root, check if the subtree starting at that node is equal to subRoot using the isSameTree function.true if any subtree matches, otherwise return false.// TreeNode class definition
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null && subRoot == null) return true;
if (root == null) return false;
return isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
private boolean isSameTree(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null || t == null) return false;
if (s.val != t.val) return false;
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
}
root and calls isSameTree which takes (O(m)) time for each node.root and (m) is the number of nodes in subRoot.The given solution efficiently checks subtrees using recursive techniques, ensuring each possible subtree is validated against subRoot.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?