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?

 

Code:

1. Recursive:

class Solution {
public:
    void findNode(vector<int> &nodes,TreeNode *node){
        nodes.push_back(node->val);
        if(node->left)
            findNode(nodes,node->left);
        if(node->right)
            findNode(nodes,node->right);
        return;
    }
    
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> nodes;
        if(!root) return nodes;
        findNode(nodes,root);
        return nodes;
    }
};

 

posted @ 2013-11-07 08:24  WinsCoder  阅读(118)  评论(0编辑  收藏  举报