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!
[codes on Leetcode]https://leetcode.com/problems/distribute-coins-in-binary-tree/solutions/5172544/move-coins-to-parent-dfs-0ms-beats-100/
[Tree & Graph Playlist]https://www.youtube.com/watch?v=9Lx7yr-tmfI&list=PLYRlUBnWnd5Kt0-3un43cwY6yT_il8NWe
# 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)
沒有留言:
張貼留言