Print a Binary Tree in Vertical Order

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

Print a Binary Tree in Vertical Order

 package algorithms;

 import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap; public class PrintVertical { private static TreeMap<Integer, List<TreeNode>> hm = new TreeMap<>(); public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
TreeNode six = new TreeNode(6);
TreeNode seven = new TreeNode(7);
TreeNode eight = new TreeNode(8);
TreeNode nine = new TreeNode(9);
root.left = two;
root.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
six.right = eight;
seven.right = nine;
printVertical(root);
for(Map.Entry<Integer, List<TreeNode>> entry: hm.entrySet()) {
System.out.println("key====="+entry.getKey());
List<TreeNode> temp = entry.getValue();
for(TreeNode node: temp){
System.out.println("node val======"+node.val);
}
}
} public static void printVertical(TreeNode root) {
helper(0, root);
} public static void helper(int cur, TreeNode root) {
if(root == null)
return; ArrayList<TreeNode> array;
if(hm.containsKey(cur)) {
array = (ArrayList<TreeNode>) hm.get(cur);
} else {
array = new ArrayList<TreeNode>();
}
array.add(root);
hm.put(cur, array);
helper(cur - 1, root.left);
helper(cur + 1, root.right);
}
}

<注> 需要注意的是使用TreeMap而不是HashMap来存遍历以后的数据。Better to use TreeMap in this case, as it will store the result in ascending order,

    which we are interested in.

上一篇:HDU 1037 - Keep on Truckin'


下一篇:解决win10装不了wifi驱动