File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
solution/0987.Vertical Order Traversal of a Binary Tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public List <List <Integer >> verticalTraversal (TreeNode root ) {
3
+ List <int []> list = new ArrayList <>();
4
+ dfs (root , 0 , 0 , list );
5
+ list .sort (new Comparator <int []>() {
6
+ @ Override
7
+ public int compare (int [] o1 , int [] o2 ) {
8
+ if (o1 [0 ] != o2 [0 ]) return Integer .compare (o1 [0 ], o2 [0 ]);
9
+ if (o1 [1 ] != o2 [1 ]) return Integer .compare (o2 [1 ], o1 [1 ]);
10
+ return Integer .compare (o1 [2 ], o2 [2 ]);
11
+ }
12
+ });
13
+ List <List <Integer >> res = new ArrayList <>();
14
+ int preX = 1 ;
15
+ for (int [] cur : list ) {
16
+ if (preX != cur [0 ]) {
17
+ res .add (new ArrayList <>());
18
+ preX = cur [0 ];
19
+ }
20
+ res .get (res .size () - 1 ).add (cur [2 ]);
21
+ }
22
+ return res ;
23
+ }
24
+
25
+ private void dfs (TreeNode root , int x , int y , List <int []> list ) {
26
+ if (root == null ) {
27
+ return ;
28
+ }
29
+ list .add (new int []{x , y , root .val });
30
+ dfs (root .left , x - 1 , y - 1 , list );
31
+ dfs (root .right , x + 1 , y - 1 , list );
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments