Skip to main content

Tree Data Structure related must solve programming questions: Part - 2


Problem Statement:

Given a tree return inorder traversal of a binary tree.

Note: Solve it using both recursion and iterative approach.

Approach - 1(Recursive approach):

Recursive approach is very simple.
  • Inorder traversal is traversing left sub tree first
  • Then visiting root and finally visiting right sub tree.
  • Break the recursion whenever there is no node available.

Code in C++:

class Solution {
        void traverse(TreeNode* node, vector<int> &res){
            if(!node)
                return;
            traverse(node->left, res);            
            res.push_back(node->val);            
            traverse(node->right, res);
        }
    public:
        vector<int> inorderTraversal(TreeNode* root){
            vector<int> res;
            traverse(root, res);
            return res;
        }
}

Approach - 2(Iterative approach):

Iterative approach is bit trickier than recursive approach.
  • Inorder traversal is traversing left sub tree first
  • Then visiting root and finally visiting right sub tree.
  • Iterative approach can be built based on the recursive approach.
  • Iterative approach can be built using the stack to store the elements.
  • Approach is:
    • Push root element to the stack and its left node, keep on doing this until there is no more left child
    • Once after reaching end of the left sub tree, pop the top element from the stack print the element.
    • Assign right child of the popped node to the current node and repeat from step 1 until the stack is non empty.

Code 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:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> elem;        
        TreeNode* curr = root;        
        while((curr) || (!elem.empty())){
            while(curr){
                elem.push(curr);
                curr = curr->left;
            } 
            curr = elem.top();
            elem.pop();
            
            res.push_back(curr->val);
            curr = curr->right;
        }
        return res;
    }
};














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

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

Leet Code: Problem #1363 Largest Multiple of Three

Given an integer array of digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order. Since the answer may not fit in an integer data type, return the answer as a string. If there is no answer return an empty string.   Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: "" Example 4: Input: digits = [0,0,0,0,0,0] Output: "0"   Constraints: 1 <= digits.length <= 10^4 0 <= digits[i] <= 9 The returning answer must not contain unnecessary leading zeros. Solution in C++: