144 Binary Tree Preorder Traversal

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].

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) {
        vector<int> result;
        if ( root == NULL ) return result;
        stack<TreeNode*> s;
        s.push(root);
        TreeNode* tnode;
        while ( ! s.empty() ) {
            tnode = s.top();
            s.pop();
            result.push_back(tnode->val);
            if ( tnode->right != NULL ) s.push(tnode->right);
            if ( tnode->left != NULL ) s.push(tnode->left);
        }
        return result;
    }
};

Notes
For a given node,

  1. print its value
  2. push its right child
  3. push its left child

results matching ""

    No results matching ""