Vertical Sum in a given Binary Tree

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));
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值