2025-02-22 Daily Challenge

Today I have done leetcode's February LeetCoding Challenge with cpp.

February LeetCoding Challenge 22

Description

Recover a Tree From Preorder Traversal

We run a preorder depth-first search (DFS) on the root of a binary tree.

At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0.

If a node has only one child, that child is guaranteed to be the left child.

Given the output traversal of this traversal, recover the tree and return its root.

 

Example 1:

Input: traversal = "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]

Example 2:

Input: traversal = "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

Input: traversal = "1-401--349---90--88"
Output: [1,401,null,349,88,90]

 

Constraints:

  • The number of nodes in the original tree is in the range [1, 1000].
  • 1 <= Node.val <= 109

Solution

class Solution {
  int dashCount = 0;
  int getNumber(const string &pattern, int &pos) {
    int result = 0;
    while(pos < pattern.length() && isdigit(pattern[pos])) {
      result *= 10;
      result += pattern[pos] - '0';
      pos += 1;
    }
    return result;
  }
  void getDashCount(const string &pattern, int &pos) {
    dashCount = 0;
    while(pos < pattern.length() && pattern[pos] == '-') {
      dashCount += 1;
      pos += 1;
    }
  }
  TreeNode *solve(const string &pattern, int &pos, int level) {
    if(!dashCount) getDashCount(pattern, pos);
    if(dashCount != level) return nullptr;
    dashCount = 0;
    TreeNode *root = new TreeNode(getNumber(pattern, pos));
    root->left = solve(pattern, pos, level + 1);
    root->right = solve(pattern, pos, level + 1);
    return root;
  }
public:
  TreeNode* recoverFromPreorder(string traversal) {
    TreeNode *root = new TreeNode();
    int pos = 0;
    root->val = getNumber(traversal, pos);
    root->left = solve(traversal, pos, 1);
    root->right = solve(traversal, pos, 1);
    return root;
  }
};

// Accepted
// 105/105 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 55.58 % of cpp submissions (21.7 MB)