Skip to content

Commit d385ad6

Browse files
committed
Add Vertical Order Traversal of a Binary Tree C#
1 parent 6d41841 commit d385ad6

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
public class Solution {
2+
private int _minX = int.MaxValue;
3+
private int _maxX = int.MinValue;
4+
private int _minY = int.MaxValue;
5+
private int _maxY = int.MinValue;
6+
7+
public IList<IList<int>> VerticalTraversal(TreeNode root) {
8+
var dict = new Dictionary<string, List<int>>();
9+
Dfs(root, dict, 0, 0);
10+
IList<IList<int>> res = new List<IList<int>>();
11+
for(int i=_minX; i<=_maxX; i++){
12+
var listY = new List<int>();
13+
for(int j=_maxY; j>=_minY; j--){
14+
var pos = i.ToString() + j.ToString();
15+
if(dict.ContainsKey(pos)){
16+
var list = dict[pos];
17+
listY.AddRange(list);
18+
}
19+
}
20+
if(listY.Count > 0){
21+
res.Add(listY);
22+
}
23+
}
24+
return res;
25+
}
26+
27+
private void Dfs(TreeNode root, Dictionary<string, List<int>> dict, int x, int y){
28+
if(root == null) return;
29+
var pos = x.ToString() + y.ToString();
30+
if(dict.ContainsKey(pos)){
31+
var list = dict[pos];
32+
list.Add(root.val);
33+
list.Sort();
34+
dict[pos]=list;
35+
}else {
36+
dict[pos] = new List<int>{ root.val};
37+
}
38+
39+
_minX = Math.Min(_minX, x);
40+
_maxX = Math.Max(_maxX, x);
41+
_minY = Math.Min(_minY, y);
42+
_maxY = Math.Max(_maxY, y);
43+
Dfs(root.left, dict, x-1, y-1);
44+
Dfs(root.right, dict, x+1, y-1);
45+
}
46+
}
47+
48+
/**
49+
* Definition for a binary tree node.
50+
* public class TreeNode {
51+
* public int val;
52+
* public TreeNode left;
53+
* public TreeNode right;
54+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
55+
* this.val = val;
56+
* this.left = left;
57+
* this.right = right;
58+
* }
59+
* }
60+
*/

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Solutions in various programming languages are provided. Enjoy it.
1313
4. [Power of Four](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/04-Power-of-Four)
1414
5. [Add and Search Word Data structure design](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design)
1515
6. [Find All Duplicates in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array)
16+
7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree)
1617

1718
## July LeetCoding Challenge
1819
Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions.

0 commit comments

Comments
 (0)