题目:
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 {
private:
vector<int> result;
public:
vector<int> preorderTraversal(TreeNode *root) {
return tmpFuction(root, result);
}
vector<int> tmpFuction(TreeNode *root, vector<int> &result) {
if(root == NULL) {
return result;
}
result.push_back(root->val);
tmpFuction(root->left, result);
tmpFuction(root->right, result);
return result;
}
};