Sunday, May 27, 2012

Path of Minimum Sum in a Binary Tree

[Question]
Given a binary tree, find the minimum sum from root to the leaf and also print that path?

[Analysis]
Apply post order traversal on binary tree. For a given node, the minimum sum from this node is, the smaller of the minimum sums between left and right sub-trees, plus the value in the node. It is tricky to deal with the node with only one child. Time Complexity is O(N). Space Complexity O(N).

[Solution]
//
// class BSTNode {
//    BSTNode left;
//    BSTNode right;
//    int    value;
// }
//
//--- JAVA ---
public static int findMinimumSumOfPath( BSTNode root, List<BSTNode> path)
{
   if (root.left ==null && root.right==null) {
    path.add(root);
    return root.value;
   }
   
   List<BSTNode> leftPath = new ArrayList<BSTNode>();
   List<BSTNode> rightPath = new ArrayList<BSTNode>();
   int leftSum= Integer.MAX_VALUE;
   int rightSum=Integer.MAX_VALUE;
   int sum=0;
   
   if (root.left!=null) 
    leftSum = findMinimumSumOfPath ( root.left, leftPath );
   if (root.right!=null) 
        rightSum = findMinimumSumOfPath ( root.right, rightPath);
   if (leftSum < rightSum) {
        path.add(root);
        path.addAll(leftPath);
        sum = root.value+leftSum;
   } 
   else {
        path.add(root);
        path.addAll(rightPath);
        sum = root.value+rightSum;
   }
   return sum;
}

//--- C++ ---
int minSumPath (Node* root, vector<int>& path) {
    if (!root) return 0;

    vector<int> path1, path2;
    int left = minSumPath(root->left, path1);
    int right=minSumPath(root->right, path2);

    path.push_back(root->val);
    if (left< right) 
        path.insert(path.end(), path1.begin(), path1.end());
    else
       path.insert(path.end(), path2.begin(), path2.end());
    
    return min(left,right) + root->val;
}

No comments:

Post a Comment