LeetCode--Binary Tree Preorder Traversal
时间:2014-05-14 20:43:22
收藏:0
阅读:242
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;
}
};
评论(0)