subtree-of-another-tree py3
This commit is contained in:
parent
58a19f7015
commit
acc9f4eaea
28
0572_subtree-of-another-tree/README.md
Normal file
28
0572_subtree-of-another-tree/README.md
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
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 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.
|
||||||
|
|
||||||
|
**Example 1:**
|
||||||
|
|
||||||
|
![](https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg)
|
||||||
|
|
||||||
|
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
|
||||||
|
Output: true
|
||||||
|
|
||||||
|
|
||||||
|
**Example 2:**
|
||||||
|
|
||||||
|
![](https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg)
|
||||||
|
|
||||||
|
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
|
||||||
|
Output: false
|
||||||
|
|
||||||
|
|
||||||
|
**Constraints:**
|
||||||
|
|
||||||
|
* 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]`.
|
||||||
|
* `-104 <= root.val <= 104`
|
||||||
|
* `-104 <= subRoot.val <= 104`
|
||||||
|
|
||||||
|
https://leetcode.com/problems/subtree-of-another-tree
|
26
0572_subtree-of-another-tree/python3/solution.py
Normal file
26
0572_subtree-of-another-tree/python3/solution.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
# Definition for a binary tree node.
|
||||||
|
# class TreeNode:
|
||||||
|
# def __init__(self, val=0, left=None, right=None):
|
||||||
|
# self.val = val
|
||||||
|
# self.left = left
|
||||||
|
# self.right = right
|
||||||
|
class Solution:
|
||||||
|
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
|
||||||
|
if subRoot is None:
|
||||||
|
return True
|
||||||
|
elif root is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if self.isSameTree(root, subRoot):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
|
||||||
|
|
||||||
|
|
||||||
|
def isSameTree(self, a, b):
|
||||||
|
if a is None and b is None:
|
||||||
|
return True
|
||||||
|
elif a is None or b is None or a.val != b.val:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return self.isSameTree(a.left, b.left) and self.isSameTree(a.right, b.right)
|
Loading…
Reference in New Issue
Block a user