I was doing a Leetcode question and I'm new to Python 3 and I found myself seriously confused about this after watching a Youtube video and Googling.
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
return(self.isSameTree(p.left, q.left) &
self.isSameTree(p.right, q.right))
What does the Optional[TreeNode]
mean in the isSameTree
function? At first I thought it was an optional array of TreeNode objects but this is totally not right. The way I wrote my code I treated variables p and q as if they were root nodes to my tree but how do I know they're root nodes?
And why does Leetcode represent the input the question as an array if it really gives you a TreeNode (root?) object? See this image if you don't understand.
Edit: Making this edit to let you all know this isn't a duplicate question, it's slightly different than what has been suggested in the comments because it pertains to an object of TreeNode and is related to inputs of trees in Leetcode so it may be beneficial to posterity.