Subtree of Another Tree

EasyTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the roots of two binary trees, root and subRoot. Return true if some node of root is the top of a subtree that is identical to subRoot, and false otherwise. "Identical" means same shape and same values at every position. The subtree rooted at a node includes **all** of that node's descendants, so a match must extend all the way to the leaves; stopping partway does not count. A tree counts as a subtree of itself.

Examples

Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
The node holding 4 has children 1 and 2 and nothing below them.
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
The 4 subtree also contains a 0 under node 2, so it is not identical.

Constraints

  • 1 <= number of nodes in root <= 2000
  • 1 <= number of nodes in subRoot <= 1000
  • -10^4 <= Node.val <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems