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?

More than 1 year has passed since last update.

leetcode 2分木

Last updated at Posted at 2023-09-21

2分木の問題を解く時の頻出アルゴリズム

再帰関数の中で「右の木」と「左の木」に分けて、再帰関数に再代入する。

Passするプログラムの形(おそらく。。。)

def 再帰関数:
    if node is None:
        return
    毎回する処理
    再帰関数(右の木)
    再帰関数(左の木)

ポイントはreturnを各場所です!

Passしたコード

# 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 sumNumbers(self, root: Optional[TreeNode]) -> int:
        nums = []
        tmp = ''
        def _make_number_from_Tree(node:TreeNode, tmp:str):
            if node is None:
                return 

            tmp += str(node.val)
            if node.right is None and node.left is None:
                nums.append(int(tmp))
            _make_number_from_Tree(node.right, tmp)
            _make_number_from_Tree(node.left, tmp)
        
        _make_number_from_Tree(root, tmp)
        return sum(nums)

失敗例1

def sumNumbers(self, root: Optional[TreeNode]) -> int:
    nums = []
    tmp = ''
    def _make_number_from_Tree(node:TreeNode, tmp:str):
        tmp += str(node.val)
        if node.right is not None:
            _make_number_from_Tree(node.right, tmp)
        if node.left is not None:
            _make_number_from_Tree(node.left, tmp)
        nums.append(int(tmp))
        return 
        
    _make_number_from_Tree(root, tmp)
    return sum(nums)

失敗例2

def sumNumbers(self, root: Optional[TreeNode]) -> int:
    nums = []
    tmp = ''
    def _make_number_from_Tree(node:TreeNode, tmp:str):
        tmp += str(node.val)
        if node.right is None:
            nums.append(int(tmp))
            return 
        else:
            _make_number_from_Tree(node.right, tmp)

        if node.left is None:
            nums.append(int(tmp))
            return
        else:
            _make_number_from_Tree(node.left, tmp)
    _make_number_from_Tree(root, tmp)
    return sum(nums)
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?