Use of three sorted data structures in C#

Problem is this: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/description/

Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).
If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.
Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.

Example 1:
Input: [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation: 
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).
Example 2:
Input: [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation: 
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.

Note:
  1. The tree will have between 1 and 1000 nodes.
  2. Each node's value will be between 0 and 1000.
The solution will be an DFS (Depth-First-Search) with pre-order traversal. You'll keep track of the x-index and the y-index. So far, standard.
The catch is the use of the proper data structures to properly store this data in the right order. Here is what I decided to do:
  • First, a Sorted Dictionary sorted by the x-index
  • Second, the value of the above data structure will be a Sorted List sorted by the y-index
  • Because of this statement, the value of the above data structure still needs to be sorted, hence I'm using as the value a Sorted Set to allow for duplicates
Putting it all together, it passes the tests. Cheers, ACC.


public class Solution
{
	public IList<IList<int>> VerticalTraversal(TreeNode root)
	{
		SortedDictionary<int, SortedList<int, SortedSet<int>>> vertical = new SortedDictionary<int, SortedList<int, SortedSet<int>>>();
		VerticalTraversal(root, 0, 0, vertical);
		List<IList<int>> solution = new List<IList<int>>();
		foreach (int x in vertical.Keys)
		{
			List<int> list = new List<int>();
			foreach (int y in vertical[x].Keys)
				foreach (int element in vertical[x][y])
					list.Add(element);
			solution.Add(list);
		}
		return solution;
	}
	private void VerticalTraversal(TreeNode root,
									int x,
									int y,
									SortedDictionary<int, SortedList<int, SortedSet<int>>> vertical)
	{
		if (root == null) return;
		if (!vertical.ContainsKey(x)) vertical.Add(x, new SortedList<int, SortedSet<int>>());
		if (!vertical[x].ContainsKey(y)) vertical[x].Add(y, new SortedSet<int>());
		vertical[x][y].Add(root.val);
		VerticalTraversal(root.left, x - 1, y + 1, vertical);
		VerticalTraversal(root.right, x + 1, y + 1, vertical);
	}
}

Comments

  1. Nice, although Python 3 comes out a winner again in terms of performance with its 36ms :)

    My solution - https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/232684/N*log(N)-solution-using-tree-traversal-and-dict-in-Python-(beats-100)

    Reply Delete
  2. Thank you for sharing. I wrote a post to share based on your code. And also I made a comment about SortedSet to remove duplicate element, which may be a problem even though the online judge of Leetcode does not provide a test case to validate the case.

    Concerns

    SortedSet will remove duplicate elements, so it may be a problem to use it. Since there is no guarantee that the binary tree may have duplicate value, and those node with the same value may be in the same horizontal, same level of tree as well.

    Here is the link:
    https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/304946/C-SortDictionary-SortedList-SortedSet-all-are-used-in-one-solution

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...