144. Binary Tree Preorder Traversal (Medium)

Given a binary tree, return the preorder traversal of its nodes' values.

For example:

Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

preorder: middle-left-right

Solution 1: recursive

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

Solution 2: iterative

vector<int> preorderTraversal(TreeNode* root) {
    vector<int> res;
    if (!root) return res;

    vector<TreeNode*> s;
    s.push_back(root);
    while (!s.empty()) {
        TreeNode *top = s.back(); s.pop_back();
        res.push_back(top->val);
        if (top->right) s.push_back(top->right);
        if (top->left) s.push_back(top->left);
    }

    return res;
}

results matching ""

    No results matching ""