Leetcode 144 Solution

This article provides solution to leetcode question 144 (binary-tree-preorder-traversal)

https://leetcode.com/problems/binary-tree-preorder-traversal

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) {
        stack<TreeNode*> s;

        if (root)
            s.push(root);

        vector<int> res;
        while (s.empty() == false)
        {
            auto p = s.top();
            s.pop();

            res.push_back(p->val);

            if (p->right)
                s.push(p->right);
            if (p->left)
                s.push(p->left);
        }

        return res;
    }
};