[Leetcode] 979. Distribute Coins in Binary Tree

这篇博客讨论了一种使用深度优先搜索(DFS)解决二叉树节点硬币分配问题的方法。在每个子树中,除根节点外的所有节点值设为1,根节点值可能不同。通过递归的DFS处理左子树和右子树,确保子树根节点的值为1。同时,博主尝试了迭代方法,但在某些情况下(如输入[0,0,null,0,0,4,null,null,0,3])出现了错误,因为额外的值没有分配给根节点,而是分给了分叉节点并重新分布。
摘要由CSDN通过智能技术生成

方法1: DFS

divide-and-conquer: by dfs, all nodes of a subtree have val of 1, except that the root node of the subtree may have different values. The dfs process will deal with root node in left subtree and root node in right subtree, to make the substree root node have val of 1.

class Solution:
    def distributeCoins(self, root: TreeNode) -> int:
        return self.dfs(root)
    
    def dfs(self, root):
        if root is None:
            return 0
        left = self.dfs(root.left)
        right = self.dfs(root.right)
        res = (left + right)
        if root.left:
            tmp = root.left.val
            root.left.val = 1
            root.val += (tmp - 1)
            res += abs(tmp - 1)
        if root.right:
            tmp = root.right.val
            root.right.val = 1
            root.val += (tmp - 1)
            res += abs(tmp - 1)
        return res

** Also tried iterative method that using parent node and the path for each node is to the root or to parent with value > 0, but it’s wrong in some cases, for example:
Input:
[0,0,null,0,0,4,null,null,0,3]
Output:
17
Expected:
15
In this case, the additional value doesn’t go to root, but to the forking node and then re-distribute.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值