Minumum Tree Path Cost

o(n);

import java.util.ArrayList;
import java.util.List;

public class NaryTreePathCost {
 private static int minCost = Integer.MAX_VALUE;
    public List<Integer> findMinCostFromRootToLeaf(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        List<Integer> curr = new ArrayList<>();
        findMinCostHelper(root, 0, curr, result);

        return result;
    }


    private void findMinCostHelper(TreeNode root, int cost, List<Integer> 
                                   curr, List<Integer> result) {
        curr.add(root.val);
        if (root.children == null || root.children.length == 0) {
            if (cost + root.val < minCost) {
                minCost = cost  + root.val;
                result.clear();
                result.addAll(new ArrayList<>(curr));
            }
            return;
        }

        for (TreeNode child : root.children) {

            findMinCostHelper(child, cost + root.val , curr, result);
            curr.remove(curr.size() - 1);
        }
    }


    public static void main(String[] args) {
     NaryTreePathCost sol = new NaryTreePathCost();

        TreeNode root = new TreeNode(1, 2);
        root.children[0] = new TreeNode(2, 2);
        root.children[1] = new TreeNode(3, 3);
        root.children[0].children[0] = new TreeNode(4, 0);
        root.children[0].children[1] = new TreeNode(2, 0);
        root.children[1].children[0] = new TreeNode(3, 0);
        root.children[1].children[1] = new TreeNode(2, 0);
        root.children[1].children[2] = new TreeNode(0, 0);

        List<Integer> result = sol.findMinCostFromRootToLeaf(root);

        for (Integer e : result) {
            System.out.print(e + " ");
        }

        System.out.println("");
        System.out.println(minCost);
    }

    static class TreeNode {
        int val;
        TreeNode[] children;

        public TreeNode(int val, int n) {
            this.val = val;
            this.children = new TreeNode[n];
        }
    }
}

results matching ""

    No results matching ""