Very interesting Tree problem

This is one of the most interesting Tree problems that I have seen in a long time. In spite of the high number of thumbs down, I think this problem exercises multiple concepts of algorithms and data structures.

The first point is that it limits the number of nodes in the tree to a very small number (2^5 - 1). With that, at least in my solution, I start by creating the full complete tree. In the process of creating it, have a hash table mapping a key to each node. The key can be calculated as a unique function from {depth, position} to a node. To make it unique, just multiply depth by a large number, and add position.

Once you have the map, go thru the input and calculate the same key, find the node and assign the value.

At this point there is still a problem where there might be multiple unused nodes. Write a DFS function to remove the unused nodes.

Finally, create a function to calculate the sum of all paths, again using DFS.

Code is down below, Happy Holidays!!! ACC.

Path Sum IV - LeetCode

666. Path Sum IV
Medium

If the depth of a tree is smaller than 5, then this tree can be represented by an array of three-digit integers. For each integer in this array:

  • The hundreds digit represents the depth d of this node where 1 <= d <= 4.
  • The tens digit represents the position p of this node in the level it belongs to where 1 <= p <= 8. The position is the same as that in a full binary tree.
  • The units digit represents the value v of this node where 0 <= v <= 9.

Given an array of ascending three-digit integers nums representing a binary tree with a depth smaller than 5, return the sum of all paths from the root towards the leaves.

It is guaranteed that the given array represents a valid connected binary tree.

Example 1:

Input: nums = [113,215,221]
Output: 12
Explanation: The tree that the list represents is shown.
The path sum is (3 + 5) + (3 + 1) = 12.

Example 2:

Input: nums = [113,221]
Output: 4
Explanation: The tree that the list represents is shown. 
The path sum is (3 + 1) = 4.

Constraints:

  • 1 <= nums.length <= 15
  • 110 <= nums[i] <= 489
  • nums represents a valid binary tree with depth less than 5.
Accepted
27,433
Submissions
45,194

public class Solution {
 public class TreeNode
 {
 public int val;
 public TreeNode left;
 public TreeNode right;
 public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
 {
 this.val = val;
 this.left = left;
 this.right = right;
 }
 }
 public int PathSum(int[] nums)
 {
 TreeNode tree = new TreeNode(-1);
 Hashtable map = new Hashtable();
 int[] currentPositionDepth = new int[5];
 for (int i = 0; i < 5; i++)
 currentPositionDepth[i] = 1;
 CreateTreeAndMap(map, tree, 1, currentPositionDepth);
 for (int i = 0; i < nums.Length; i++)
 {
 int depth = nums[i] / 100;
 int position = (nums[i] / 10) % 10;
 int value = nums[i] % 10;
 int key = depth * (100 + 7) + position;
 TreeNode node = (TreeNode)map[key];
 node.val = value;
 }
 DeleteUnusedNodes(tree);
 int retVal = 0;
 SumPaths(tree, 0, ref retVal);
 return retVal;
 }
 private void SumPaths(TreeNode node,
 int currentPathSum,
 ref int totalSum)
 {
 if (node == null) return;
 if (node.left == null && node.right == null)
 {
 totalSum += currentPathSum + node.val;
 return;
 }
 SumPaths(node.left, currentPathSum + node.val, ref totalSum);
 SumPaths(node.right, currentPathSum + node.val, ref totalSum);
 }
 private void DeleteUnusedNodes(TreeNode tree)
 {
 if (tree == null) return;
 if (tree.left != null)
 {
 if (tree.left.val != -1) DeleteUnusedNodes(tree.left);
 else tree.left = null;
 }
 if (tree.right != null)
 {
 if (tree.right.val != -1) DeleteUnusedNodes(tree.right);
 else tree.right = null;
 }
 }
 private void CreateTreeAndMap(Hashtable map,
 TreeNode node,
 int currentDepth,
 int[] currentPositionDepth)
 {
 int key = currentDepth * (100 + 7) + currentPositionDepth[currentDepth - 1];
 currentPositionDepth[currentDepth - 1]++;
 map.Add(key, node);
 if (currentDepth + 1 <= 5)
 {
 node.left = new TreeNode(-1);
 CreateTreeAndMap(map, node.left, currentDepth + 1, currentPositionDepth);
 node.right = new TreeNode(-1);
 CreateTreeAndMap(map, node.right, currentDepth + 1, currentPositionDepth);
 }
 }
}

Comments

  1. Actually there is an improvement: you don't need to remove the unused nodes, the following adjustment to SumPaths function would take care of the unused nodes, saving some milliseconds:

    private void SumPaths(TreeNode node,
    int currentPathSum,
    ref int totalSum)
    {
    if (node == null || node.val == -1) return;

    if ((node.left == null || node.left.val == -1) &&
    (node.right == null || node.right.val == -1))
    {
    totalSum += currentPathSum + node.val;
    return;
    }

    SumPaths(node.left, currentPathSum + node.val, ref totalSum);
    SumPaths(node.right, currentPathSum + node.val, ref totalSum);
    }

    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...