144. Binary Tree Preorder Traversal

Given a binary tree, return thepreordertraversal of its nodes' values.

For example: Given binary tree[1,null,2,3],

   1
    \
     2
    /
   3

return[1,2,3].

Thoughts:

Using Stack

Code

/**
 * 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 *> treeSt;
        vector<int> answer;
        if(!root) return vector<int>();

        treeSt.push(root);
        while(!treeSt.empty()){
            TreeNode* cur = treeSt.top();
            answer.push_back(cur->val);
            treeSt.pop();
            if(cur->right)treeSt.push(cur->right);
            if(cur->left)treeSt.push(cur->left);
        }

        return answer;
    }
};

Code 2: Check from the pop

Code (Python)

Last updated

Was this helpful?