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:
void preorder(TreeNode *root, vector<int> &temp)
{
if(!root)
return ;
temp.push_back(root->val);
preorder(root->left,temp);
preorder(root->right,temp);
}
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> result;
preorder(root, result);
return result;
}
};