Posted on

Description

Submission(Recursive)

/**
 * 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 {
    vector<int> rets;
    void preorder(TreeNode* root) {
        if(!root) return;
        rets.push_back(root->val);
        preorder(root->left);
        preorder(root->right);
    }
public:
    vector<int> preorderTraversal(TreeNode* root) {
        preorder(root);
        return rets;
    }
};

Submission(Iterative)

/**
 * 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> preorderTraversal(TreeNode* root) {
        if(root == nullptr) return {};

        stack<TreeNode*> nodes;
        nodes.push(root);
        vector<int> rets;

        while(!nodes.empty()) {
            auto* node = nodes.top();
            nodes.pop();
            rets.push_back(node->val);
            
            if(node->right) nodes.push(node->right);
            if(node->left) nodes.push(node->left);
        }

        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *