herrDeng網內搜尋

自訂搜尋

Ads

2024年5月18日 星期六

C++ python後序走訪解Leetcode 979 Distribute Coins in Binary Tree


C++ python後序走訪解Leetcode 979  Distribute Coins in Binary Tree
解Leetcode 979. Distribute Coins in Binary Tree。學過二元樹的一定會使用post-order走訪,重點不是coding有多容易或多困難,重點是二元樹分錢最好是從葉節點開始,孩子要孝順父母!Python code請進
--------
Solution to Leetcode 979. Distribute Coins in Binary Tree. Those who have learned binary trees will bedefinitely able to use post-order visits. The point is not how easy or difficult coding is. The point is that it is best to start from the leaf nodes in binary trees. Children should be filial to their parents!

# 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 distributeCoins(self, root: Optional[TreeNode]) -> int:
        #move coins to parent DFS
        def f(root, parent):
            if root==None: return 0
            moves=f(root.left, root)+f(root.right, root)
            x=root.val-1
            if parent!=None: parent.val+=x
            moves+=abs(x)
            return moves
        return f(root, None)

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章