Share My Recursive and Iterative C++ Solution


  • 0
    S
    //Solution 1 -- 3 ms 0.57% 
    /**
     * 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> result;
        vector<int> preorderTraversal(TreeNode* root) {
            if(!root) return result;
            result.push_back(root->val);
            if(root->left) preorderTraversal(root->left);
            if(root->right) preorderTraversal(root->right);
            return result;
        }
    };
    
    //Solution 2 -- 0 ms 44.13%
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> result;
            if(!root) return result;
            TreeNode* cur = root, *pre = NULL;
            stack<TreeNode*> stk;
            while(cur || !stk.empty()){
                while(cur){
                    result.push_back(cur->val);
                    stk.push(cur);
                    pre = cur;
                    cur = cur->left;
                }
                cur = stk.top();
                if(cur->right && pre != cur->right)
                    cur = cur->right;
                else{
                    stk.pop();
                    pre = cur;
                    cur = NULL;
                }
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.