상위 150개 인터뷰중간

다른 트리의 하위 트리

'다른 트리의 하위 트리' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

중간

두 이진 트리 root와 subRoot의 루트가 주어지면 subRoot의 구조와 노드 값이 동일한 루트의 하위 트리가 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.

이진 트리 트리의 하위 트리는 트리의 노드와 이 노드의 모든 자손으로 구성된 트리입니다. 트리 트리는 그 자체의 하위 트리로 간주될 수도 있습니다.

트리는 레벨 순서 목록으로 표시됩니다. isSubtree(root: list, subRoot: list) -> bool 함수를 구현하세요.

제약
  • The number of nodes in the root tree is in the range [1, 2000]
  • The number of nodes in the subRoot tree is in the range [1, 1000]
  • -10000 <= root.val <= 10000
  • -10000 <= subRoot.val <= 10000

Example 1
Input
[3,4,5,1,2], [4,1,2]
Output
True
Explanation

The subtree rooted at node 4 in the main tree matches subRoot exactly.

Example 2
Input
[3,4,5,1,2,None,None,None,None,0], [4,1,2]
Output
False
Explanation

The subtree rooted at 4 in the main tree has an extra node 0 under 2, so it doesn't match subRoot.

Need a Hint?
세트나 힙과 같은 트리 관련 데이터 구조를 사용해 보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

편집기에서 열기
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.