Minimum length sum path

Given a binary tree, find out the minimum length sum path form root to leaf with sum S. What about finding minimum length sum path for BST? How does BST improve the search?

For example, the min length path for sum S=13 in T1 is 2 (6–>7 not, 6–>4–>3). For T2 min length path for sum S=3 is 3 (3–> -2 –>3).

    
                    T1                T2        
                    6                  3                   
                /      \             /
               4        7           -2
            /     \                    \
           3       5                     2               

For a binary tree, in order to find path re usually do a DFS search. So, we will do a modified DFS in this case to track min length path.

  1. Compute difference between sum and current node value. Also keep tracking length of the current path.
  2. If the difference is zero and the node is a leaf that means we got a path. Increase the path length by 1 and return it.
  3. Otherwise, we keep searching for the path down to current nodes left and right child for the new sum = difference. Return the length of the minimum of the two paths.

This approach is actually traversing all the paths of the tree and hence all the nodes.. So, the time complexity is O(n).

private int minLenSumPathBT(final TreeNode root, final int sum, final int len) {
    if (root == null) {
        return Integer.MAX_VALUE;
    }

    final int diff = sum - root.key;
    if (diff == 0 && root.left == null && root.right == null) {
        return len + 1;
    } else {
        return Math.min(minLenSumPathBST(root.left, diff, len + 1), minLenSumPathBST(root.right, diff, len + 1));
    }
}

 

Min length sum-path for BST
With a BST we have an added advantage that we know all the nodes on the left is less than the current node and all the nodes on the right are greater than the current node.

For example with T1 and S=13, while we are at node 6 then we look for min path by traversing both left and right subtree for sum S=(13-6)=7. But if we knew that T1 is a BST while traversing node 6 then we could simply ignore the left subtree because the remaining sum 7 is greater than current node.

So, while doing a DFS to search for a minLen path in a BST we actually can take informed decision at each node to either go left or right based on the remaining sum to search and hence cutting down the search space in half in average case. This will guarantee finding the minimum length path because –

  1. If current node value is equal to sum and it is a leaf node than we have a complete path. If it is not a leaf then we need to find a zero sum minLen path along one of its subtrees.
  2. If current node value is greater than (or equal to) the remaining sum i.e. value>=(sum-value) then we should search for new sum=(sum-value) in the left sub tree because – if a path exists in the left subtree, it must be the shorter than any possible path in the right subtree, since all nodes at left is smaller than those at right. If such path doesn’t exists, only then we also search in the right subtree.
  3. Similarly, If current node value is smaller than the remaining sum i.e. value<(sum-value) then we should search for new sum=(sum-value) in the right sub tree because – if a path exists in the right subtree, it must be the shorter than any possible path in the right subtree, since all nodes at right is greater than those at left. If such path doesn’t exists, only then we also search in the left subtree.

So, average case complexity will be improved to O(lgn) with a complete BST. However, the worst case complexity will be O(n) in case where we have to search both left and right subtree for the remaining sum.

private int minLenSumPathBST(final TreeNode root, final int sum, final int len) {
    if (root == null) {
        return Integer.MAX_VALUE;
    }

    // find the remaining sum as we are including current node in the current path
    final int remainingSum = sum - root.key;
    // If remaining sum is zero and it is a leaf node then we found a complete path from root to a leaf.
    if (remainingSum == 0 && root.left == null && root.right == null) {
        return len + 1;
    }
    // If remaining sum is less than current node value then we search remaining in the left subtree.
    else if (remainingSum <= root.key) {
    	 int l = minLenSumPathBST(root.left, remainingSum, len + 1);
         // if search in left subtree fails to find such path only then we search in the right subtree
         if (l == Integer.MAX_VALUE) {
             l = minLenSumPathBST(root.right, remainingSum, len + 1);
         }

         return l;
        
    }
    // If remaining sum is greater than current node value then we search remaining in the right subtree.
    else {
    	 int l = minLenSumPathBST(root.right, remainingSum, len + 1);
         // if search in right subtree fails to find such path only then we search in the left subtree
         if (l == Integer.MAX_VALUE) {
             l = minLenSumPathBST(root.left, remainingSum, len + 1);
         }

         return l;
    }
}

8 thoughts on “Minimum length sum path

  1. Your first code should have a proper name as the name minLenSumPathBST suggests something related to BST but in fact your code is for BT. right?

      • could you explain more how the worst case complexity is O(n) for BST? I guess if there indeed a path exists with sum S then the BST will always take the correct direction (left or right) at each step and eventually get to the leaf? This ensures an O9lgn) time.

          • hey Mystic! great question. Yes, complexity is indeed O(lgn) if the BST is complete and balanced once. But in worst case BST could be unbalanced and incomplete such as chain of right branch and no left branch. In this case worst case complexity is O(n).

  2. If the tree T1 mentioned in the post, is changed like below,
    6
    / \
    4 117
    / \
    3 5

    The code returns Integer.MAX_VALUE as the min length, where as it should it print 3 (path: 6 -> 4 -> 3). What I think is the above code works well only if a particular path sum exists in both the subtrees, then by going left or right as needed we can arrive at the answer. But for cases like above, we need to traverse both left and right subtrees to arrive at the correct answer.

    • Hey, rookie. Thanks for the comment!

      Yes you are right. In case the probe in left or right return with a max_value then we need to search in the other side of the probe. But we need an indication to stop this cyclic process to stop the recursion. What we can do , we can pass a visited data structure to signal whether the other probe has already been traversed. thoughts?

      • I actually corrected the case in my code but forget to upload the solution. Thanks for catch.

Comments are closed.