package tree;
import java.util.HashMap;
import java.util.Set;
public class VerticalSum {
/**
* Vertical Sum in a given Binary Tree
Given a Binary Tree, find vertical sum of the nodes that are in same vertical line.
Print all sums through different vertical lines.
Examples:
1
/ \
2 3
/ \ / \
4 5 6 7
The tree has 5 vertical lines
Vertical-Line-1 has only one node 4 => vertical sum is 4
Vertical-Line-2: has only one node 2=> vertical sum is 2
Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12
Vertical-Line-4: has only one node 3 => vertical sum is 3
Vertical-Line-5: has only one node 7 => vertical sum is 7
* @param args
*/
public static void verticalsum(TreeNode root,int k,HashMap<Integer, Integer> hashMap){
if(root==null) return;
//HashMap<Integer, TreeNode> hashMap = new HashMap<>();
if(hashMap.containsKey(k)){
int sum = hashMap.get(k);
sum+=root.value;
hashMap.put(k, sum);
}else{
hashMap.put(k, root.value);
}
verticalsum(root.left, k-1, hashMap);
verticalsum(root.right, k+1, hashMap);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
HashMap<Integer, Integer> hashMap = new HashMap<>();
verticalsum(root, 0, hashMap);
Set<Integer> set = hashMap.keySet();
for(int temp:set){
System.out.println(hashMap.get(temp));
}
}
}
Vertical Sum in a given Binary Tree
最新推荐文章于 2019-03-08 13:32:23 发布