Given a BST and a value x. Find two nodes in the tree whose sum is equal x.
Additional space: O(height of the tree). It is not allowed to modify the tree.
The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X.
The time complexity of this solution will be O(n^2).
A Better Solution is to create an auxiliary array and store Inorder traversal of BST in the array.
The array will be sorted as Inorder traversal of BST always produces sorted data.
Once we have the Inorder traversal, we can pair in O(n) time.
This solution works in O(n) time, but requires O(n) auxiliary space.
A space optimized solution is to first in-place convert BST to Doubly Linked List (DLL),
then find pair in sorted DLL in O(n) time.
This solution takes O(n) time and O(Logn) extra space, but it modifies the given BST.
The solution discussed below takes O(n) time, O(Logn) space and doesn’t modify BST.
The idea is same as finding the pair in sorted array.
We traverse BST in Normal Inorder and Reverse Inorder simultaneously.
In reverse inorder, we start from the rightmost node which is the maximum value node.
In normal inorder, we start from the left most node which is minimum value node.
We add sum of current nodes in both traversals and compare this sum with given target sum.
If the sum is same as target sum, we return true.
If the sum is more than target sum, we move to next node in reverse inorder traversal,
otherwise we move to next node in normal inorder traversal.
If any of the traversals is finished without finding a pair, we return false.
Following is C++ implementation of the last approach:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
Given a binary tree and a sum, determine if the tree has a root-to-leaf path
such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.