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^4 <= Node.val <= 10^4
Test Cases
1 2 3 4 5 6 7 8
|
class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
|
solution_test.py1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import pytest
import sys sys.path.insert(0, '..') 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.py1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| from typing import Optional
import sys sys.path.insert(0, '..') from _utils.binary_tree import TreeNode
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
|