subtree-of-another-tree py3

This commit is contained in:
Sangeeth Sudheer 2022-04-25 21:43:37 +05:30
parent 58a19f7015
commit acc9f4eaea
2 changed files with 54 additions and 0 deletions

View 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

View 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)