Last active
September 28, 2018 17:13
-
-
Save thmain/d2d1adc74f0133feaeb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Set; | |
import java.util.TreeMap; | |
public class VerticalOrderSum { | |
public static TreeMap<Integer, Integer> ht = new TreeMap<>();; | |
public static int level; | |
public void vertical(Node root, int level) { | |
if (root == null) { | |
return; | |
} | |
vertical(root.left, level+1); | |
if (ht.get(level) != null) { | |
int y = ht.get(level); | |
ht.put(level, root.data + y); | |
} else { | |
ht.put(level, root.data); | |
} | |
vertical(root.right, level-1); | |
} | |
public void printResult(TreeMap ht) { | |
// Iterator it = ht.keySet().iterator(); | |
Set<Integer> i = ht.keySet(); | |
for (int keys : i) { | |
System.out.println("Level " + keys + " Sum : " + ht.get(keys)); | |
} | |
} | |
public static void main(String args[]) { | |
Node root = new Node(1); | |
root.left = new Node(2); | |
root.right = new Node(3); | |
root.left.left = new Node(4); | |
root.left.right = new Node(5); | |
root.right.left = new Node(6); | |
root.right.right = new Node(7); | |
VerticalOrderSum p = new VerticalOrderSum(); | |
p.vertical(root, 0); | |
p.printResult(ht); | |
} | |
} | |
class Node { | |
int data; | |
Node left; | |
Node right; | |
public Node(int data) { | |
this.data = data; | |
left = null; | |
right = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment