Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

100. Same Tree

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Example 1:

1
2
Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

1
2
Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

1
2
Input: p = [1,2,1], q = [1,1,2]
Output: false

判斷2棵樹一不一樣,就遍歷時看節點一不一樣。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
T: O(N), S: O(log(N))
# 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, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
# p and q are both None
if not p and not q:
return True
# one of p and q is None
if not q or not p:
return False
if p.val != q.val: # root equal
return False
return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left) # leaf equal

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels