100. Same Tree
Problem
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.
https://leetcode.com/problems/same-tree/
Example 1:

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

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

Input:
p = [1,2,1], q = [1,1,2]
Output:false
Constraints:
- The number of nodes in both trees is in the range
[0, 100]. -10⁴ <= Node.val <= 10⁴
Test Cases
# 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:solution_test.py下载完整源码
import pytest
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from _utils.binary_tree import build_tree
from solution import Solution
null = None
@pytest.mark.parametrize('p, q, expected', [
([1,2,3], [1,2,3], True),
([1,2], [1,null,2], False),
([1,2,1], [1,1,2], False),
])
class Test:
def test_solution(self, p, q, expected):
sol = Solution()
assert sol.isSameTree(build_tree(p), build_tree(q)) == expected
Thoughts
在 572. Subtree of Another Tree 中包含了。
按前序(pre-order,NLR)同步遍历两棵二叉树。对于当前节点,如果一边有而另一边缺失,或者两边节点的值不同,直接返回 false。
Code
solution.py下载完整源码
from typing import Optional
# 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:
stack = []
while p or q or stack:
if (not not p) != (not not q):
return False
elif p:
if p.val != q.val:
return False
stack.append((p, q))
p = p.left
q = q.left
elif stack:
p, q = stack.pop()
p = p.right
q = q.right
return True
评论需要 JavaScript。