@@ -96,4 +96,45 @@ public List<List<Integer>> verticalOrder(TreeNode root) {
96
96
}
97
97
}
98
98
99
+ public static class Solution3 {
100
+ public List <List <Integer >> verticalOrder (TreeNode root ) {
101
+ if (root == null ) {
102
+ return new ArrayList <>();
103
+ }
104
+ TreeMap <Integer , List <Integer >> map = new TreeMap <>();
105
+ Queue <NodeWithIndex > queue = new LinkedList <>();
106
+ queue .offer (new NodeWithIndex (root , 0 ));
107
+ while (!queue .isEmpty ()) {
108
+ int size = queue .size ();
109
+ for (int i = 0 ; i < size ; i ++) {
110
+ NodeWithIndex nodeWithIndex = queue .poll ();
111
+ List <Integer > thisList = map .getOrDefault (nodeWithIndex .index , new ArrayList <>());
112
+ thisList .add (nodeWithIndex .node .val );
113
+ map .put (nodeWithIndex .index , thisList );
114
+ if (nodeWithIndex .node .left != null ) {
115
+ queue .offer (new NodeWithIndex (nodeWithIndex .node .left , nodeWithIndex .index - 1 ));
116
+ }
117
+ if (nodeWithIndex .node .right != null ) {
118
+ queue .offer (new NodeWithIndex (nodeWithIndex .node .right , nodeWithIndex .index + 1 ));
119
+ }
120
+ }
121
+ }
122
+ List <List <Integer >> result = new ArrayList <>();
123
+ for (int index : map .keySet ()) {
124
+ result .add (map .get (index ));
125
+ }
126
+ return result ;
127
+ }
128
+
129
+ class NodeWithIndex {
130
+ TreeNode node ;
131
+ int index ;
132
+
133
+ public NodeWithIndex (TreeNode node , int index ) {
134
+ this .node = node ;
135
+ this .index = index ;
136
+ }
137
+ }
138
+ }
139
+
99
140
}
0 commit comments