Skip to main content

LeetCode Problem: 1028. Recover a Tree From Preorder Traversal

Problem Statement:
Recover binary tree from its given preorder traversal string. The string is given in the format: Dashes followed by value. The number of dashes convey its depth and value refers to the node value.

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

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

Example 3:
Input:
string = "1-401--349---90--88";
Output:
[1,401,null,349,88,90].

Approach to the solution:
  1. Calculate value and its depth
  2. Check if right child is present. If yes then move to right child then go to step 2 again until depth of the node is reached.
  3. Else move to left and then go to step 2 again until depth of the node is reached.
  4. Once the calculated depth is reached.
  5. If left child of the node is null, create a new node and assign left child of the node.
  6. Else create a new node and assign it to right child.
  7. Continue from step 1 again until end of the string is reached.
Solution in C++:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* recoverFromPreorder(string S) {
            int iter = 0;
            int depth = 0;
            int num   = 0;
        num   = GetNum(S, iter);
        TreeNode* root = new TreeNode(num);
        while(iter < S.length()){
            depth = GetDepth(S, iter);
            num   = GetNum(S, iter);
            InsertIntoTree(root, depth, num);
        }
        return root;
    }
private:

    void InsertIntoTree(TreeNode* node, int depth, int value){
        while(--depth > 0){
            if(node->right){
                node = node->right;
            } else if(node->left){
                node = node->left;
            }
        }
        TreeNode *temp = new TreeNode(value);
        if(node->left == nullptr){
            node->left = temp;
        } else {
            node->right = temp;
        }
    }
    int GetDepth(string S, int &iter){
            int count = 0;
        while(S[iter] == '-'){
            ++iter;
            ++count;
        }
        return count;
    }   
    int GetNum(string S, int &iter){
            int num = 0;
        while(S[iter] != '-' && iter < S.length()){
            num = num * 10 + (int)(S[iter] - 48);
            ++iter;
        }
        return num;
    }
};

Comments

Popular posts from this blog

Leet Code: Problem #710 Random Pick with Blacklist

Given a blacklist  B containing unique integers from [0, N) , write a function to return a uniform random integer from [0, N) which is NOT  in B . Optimize it such that it minimizes the call to system’s Math.random() . Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N)  does NOT include N. See interval notation . Example 1: Input: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] Output: [null,0,0,0] Example 2: Input: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] Output: [null,1,1,1] Example 3: Input: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] Example 4: Input: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] Output: [null,1,3,1] Explanation of Input Syntax: The input is two lists: the subroutines called and their argume...

Leet Code: Problem: 355. Design Twitter

Problem Statement: Design basic twitter which lets user follow and unfollow other users and show the latest new feed related to the current user and the user followers. Implement the following APIs void postTweet(int userId, int tweetId):     Stores the tweetId against the user ID. void follow(int followerId, int followeeId):     Marks that follower ID as following followee ID void unfollow(int followerId, int followeeId):     Marks that follower ID as unfollowing followee ID vector<int> getNewsFeed(int userId):     Returns the set of the latest 10 tweetIDs which include the current user tweetIDs and tweetIDs of the user that the follower if following. Approach to the problem: First we need to store the user IDs of the people a particular user is following To store that we can use map. To optimize things instead of storing list of followers, it is better to store them in a set for quicker access. So the followers data str...

LeetCode: Problem #1402. Reducing Dishes

Problem Statement: A chef has collected the data on the review for his dishes. Our Chef will take just 1 unit of time to prepare a dish. Our job is to tell him the dishes he has to make in the order to achieve maximum benefit. The maximum benefit is calculated using the formula time[i] * (review ratings). Example 1: Input: reviews = [-1, -10, -9, 0, 5] Output: 14 Explanation: Considering the dishes in the order of -1, 0 ,5 the calculation will be (-1 * 1 + 0 * 2 + 5 * 3) = 14 Example 2: Input: reviews = [6,5,4] Output: 32 Explanation: Considering the dishes in the order of 4, 5, 6 the calculation will be (4 * 1 + 5 * 2 + 6 * 3) = 32 Approach to the solution: Sort the given reviews so that we can concentrate only on maximum benefited reviews. Make cumulative sums from the end. This will help in deciding till which we have to consider the summation. Now start from the end at add the previous array of cumulative sums until a negative number is encountered. We have to iterate in reverse or...