0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

100. Same Tree

Posted at

問題内容

入力された二分木がすべてのノードについて同じ数字を持っているか調べ同じ構造の二分木か判別する関数を作る。

解答例

sample
# 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:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

ポイント

  • 両方のrootノードについて、どちらもNullなら同じ二分木、片方だけNullなら異なる二分木という処理を書き忘れないように注意
  • 再帰呼び出しを使うことで、rootとleftに分岐する部分、そしてrightに分岐する部分が全て一致するかを簡潔に判別できる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?