<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cassey Shao on Medium]]></title>
        <description><![CDATA[Stories by Cassey Shao on Medium]]></description>
        <link>https://medium.com/@casseyshao?source=rss-17c826edf15e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FWKrsVqFDNTEgjw_pmlNsA.jpeg</url>
            <title>Stories by Cassey Shao on Medium</title>
            <link>https://medium.com/@casseyshao?source=rss-17c826edf15e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:09:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@casseyshao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A minimum path tree problem where each node has a value]]></title>
            <link>https://casseyshao.medium.com/a-minimum-path-tree-problem-where-each-node-has-a-value-7fe76e7e3cbe?source=rss-17c826edf15e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fe76e7e3cbe</guid>
            <category><![CDATA[minimum-path]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[coding-question]]></category>
            <dc:creator><![CDATA[Cassey Shao]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 18:37:17 GMT</pubDate>
            <atom:updated>2024-09-15T23:13:00.217Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Problem</strong></h3><p>You are given a tree where each node has a value (it can be positive or negative) and an arbitrary number of children nodes. The problem asks you to return the cost of the minimum path, where the cost of the minimum path is calculated by adding all the node values in a path from root to leaf.</p><p>A tree node has the following structure:</p><pre>class TreeNode:<br>    def __init__(self, cost, children = None):<br>        self.cost = cost<br>        self.children = children # Array of TreeNode objects.</pre><p>For example, for the following tree, the output should be 9. I.e., 1+3+5 is smaller than 1+7+4 and smaller than 1+3+6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCsgHyJ752Z4druc0zrU8A.png" /><figcaption>A tree where the minimum cost of all paths is 9.</figcaption></figure><p>Another example is the tree below. The output should be -4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbF7viGKMjBvQyE5WurwRQ.png" /><figcaption>A tree where the minimum cost of all paths is -4.</figcaption></figure><p>Finally, if the root has no children, the cost returned should be the root value.</p><h3><strong>Solution</strong></h3><p>Because each node can take on any positive or negative value, we will need to check all paths in order to guarantee that we have found the minimum cost for the entire tree. We want to also minimize the number of times that we need to check each node in the tree. This is to ensure that our solution will run in optimal time.</p><p>We can use a stack to build a solution which checks all paths and runs in O(n) time, where n is the number of nodes in the tree. The stack will carry relevant information after visiting a node through 2-element subarrays. In these 2-element subarrays, the first element will be the cost of the current path, and the second element will be the next node in the current path.</p><p>The logic is to initialize the stack with a 2-element subarray, where the first element is 0 and the second element is the root node. We will also initialize a variable min_cost to store the minimum cost seen across all paths. While the stack is not empty, we will pop an entry. We will then get the cost of the path by adding the current cost (at element 0 of the entry) and the next node value (at element 1 of the entry). If the next node has children, for each child, we will push into the stack an entry with the updated cost of the path and the child. If the next node does not have children, we will compare if the updated cost of the root to leaf path is smaller than the current value stored in min_cost. If it is, we will update min_cost. After all paths have been checked (i.e., the stack is empty), we will return min_cost.</p><pre>class TreeNode:<br>    def __init__(self, cost, children = None):<br>        self.cost = cost<br>        self.children = children # Array of TreeNode objects.<br><br># (O(n)) -&gt; only looking at each node once.<br>def solution(root):<br>    min_cost = None<br><br>    stack = [[0, root]]<br><br>    while stack: # While stack is not empty.<br>        curr = stack.pop()<br>        curr_path_cost = curr[0]<br>        curr_path_node = curr[1]<br>        curr_node_cost = curr_path_node.cost<br><br>        if curr_path_node.children:<br>            for child in curr_path_node.children:<br>                stack.append([curr_path_cost+curr_node_cost, child])<br>        else:<br>            if (min_cost is None) or ((curr_path_cost+curr_node_cost) &lt; min_cost):<br>                min_cost = curr_path_cost+curr_node_cost<br><br>    return min_cost<br><br># Testing<br>leaf0 = TreeNode(-20)<br>leaf1 = TreeNode(7)<br>leaf2 = TreeNode(18)<br>child0 = TreeNode(15, [leaf0])<br>child1 = TreeNode(3)<br>child2 = TreeNode(2, [leaf1, leaf2])<br>root = TreeNode(1, [child0, child1, child2])<br>print(solution(root))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fe76e7e3cbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>