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

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

/**
 * Definition for binary tree
 * 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> ans;
        iter(root,ans);
        return ans;
    }
    void iter(TreeNode *root, vector<int>& vec) {
        if(root == NULL) return;
        
        vec.push_back(root->val);
        iter(root->left,vec);
        iter(root->right,vec);
    }
};

 

posted on 2014-12-03 11:43  code#swan  阅读(82)  评论(0)    收藏  举报

导航