问题
How to find the vertical sum of a binary tree.
For example, Consider the binary tree below,
1
/ \
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
/ \ / \ / \ / \
5 9 1 3 6 7 5 5
For the above tree, Vertical sum should be calculated as follows,
- Line 1: 5
- Line 2: 4
- Line 3: 2,9,1
- Line 4: 5
- Line 5: 1,3,6
- Line 6: 6
- Line 7: 3,7,5
- Line 8: 7
- Line 9: 5
Output should be:
5,4,12,5,10,6,15,7,5
回答1:
First you should find the positions, you can do this by counting number of left and rights spend to reach specific node:
1 : l = 0, r = 0
/ \
/ \
l=1,r=0 2 3 : l = 0, r = 1.
/ \ / \
... 4...5 6...7 ....
Simply you can traverse your binary tree and finally calculate LorR = NumberOfLeft - NumberOfRights
for each node, then group this numbers (by their LorR
value) together and find each groups sum (print them from most positive to most negative value of LorR
).
Update: This doesn't answers for tree of height more than two, we can fix this problem with little modification in algorithm.
We can see tree as pyramid, each vertex of pyramid has length 1, after each branch remaining part of branch is equal to what passed in latest move, we show this in picture for tree of height 3:
1
/ \
/ \
/ \
2 3 upto this we used 1/2 size of pyramid
/ \ / \
/ \ / \
4 5 6 7 upto this we used 1/2 + 1/4 part of pyramid
/ \ / \ / \ / \
5 9 1 3 6 7 5 5 upto this we used 1/2 + 1/4 + 1/4 part of pyramid
This means in each step we calculate left values by their height (in fact each time multiply of 1/2 will be added to left value, except last time, which is equal to h-1 st value).
So for this case we have: 1 in root is in group 0, 3 in leaf is in group -1/2 + 1/4 + 1/4 = 0, 6 in leaf is in group 1/2 - 1/4 - 1/4 = 0
1 in leaf is in -1/2 + 1/4 - 1/4 = -1/2 and so on.
For preventing from rounding of 1/(2^x) to zero or other problems we can multiply our factors (1/2, 1/4, 1/8,...) to 2h-1. In fact in the first case I wrote we can say factors are multiplied by 22-1.

回答2:
As far as i understood moving left is -1, moving right is +1. You can use modified dfs. Here is assume that add(col, value)
is defined
dfs(col, node)
begin
add(col, node.value)
if(haveLeft)
dfs(col-1, left)
if(haveRight)
dfs(col+1, right)
end
Assuming, that add works in O(1) (using HashMap or simple array for example), this works in O(n).
回答3:
A brute force method in pseudocode:
columnAdd(tree):
sumPerColumn = new Map<int,int>();
traverse(tree.root, sumPerColumn, 0);
return sumPerColumn;
traverse(node, sumPerColumn, currentColumn):
sumPerColumn[currentColumn] ++;
traverse(node.left, sumPerColumn, currentColumn-1);
traverse(node.right, sumPerColumn, currentColumn+1);
this would yield:
{-2: 4,
-1: 2,
0: 12,
1: 3,
2: 7}
来源:https://stackoverflow.com/questions/9646575/vertical-sum-of-a-binary-tree