LeetCode--Binary Tree Preorder Traversal

时间:2014-05-14 20:43:22   收藏:0   阅读:242

Binary Tree Preorder Traversal

 Total Accepted: 18022 Total Submissions: 51784My Submissions

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?


 法一,递归

class Solution {
public:
    void preOrder(TreeNode* root,vector<int>& vectorStorage)
    {
        if(root!=NULL)
        {
            vectorStorage.push_back(root->val);
            preOrder(root->left,vectorStorage);
            preOrder(root->right,vectorStorage);
        }
    }

    vector<int> preorderTraversal(TreeNode *root)
    {
        vector<int> vectorTemp;
        preOrder(root,vectorTemp);
        return vectorTemp;

    }
};


LeetCode--Binary Tree Preorder Traversal,布布扣,bubuko.com

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!