Simple straightforward c++ iterative solution


  • 0
    H
    /**
     * 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> result;  
            
            if(root == NULL) {
                return result;
            }
            
            vector<TreeNode*> nodeStack;
            
            nodeStack.push_back(root);
            
            while(!nodeStack.empty()) {
                TreeNode* node = nodeStack.back();
                nodeStack.pop_back();
                
                result.push_back(node->val);
                
                if(node->right != NULL) {
                    nodeStack.push_back(node->right);
                }
            
                if(node->left != NULL) {
                    nodeStack.push_back(node->left);
                }           
            }
            
            return result;
        }
    };

Log in to reply
 

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