Binary Tree Preorder Traversal @LeetCode

PROBLEM :

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Recursive Solution)
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
    vector<int> vec ;
    if(root==NULL)
    return vec ;
   
    preorder(root,vec) ;
    return vec ;
    }
   
    void preorder(TreeNode* root,vector<int> &vec){
    if(root==NULL)
    return ;
   
    vec.push_back(root->val) ;
    preorder(root->left,vec) ;
    preorder(root->right,vec) ;
}
};

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Iterative Solution)
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> vec ;
        if(root==NULL)
        return vec ;
       
        stack<TreeNode*> sta ;
        sta.push(root) ;
       
        while(!sta.empty()){
        TreeNode* curr=sta.top() ;
sta.pop() ;

vec.push_back(curr->val) ;

if(curr->right)
sta.push(curr->right) ;
if(curr->left)
sta.push(curr->left) ;
}
return vec ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )