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?
给定一棵二叉树,返回树的前序遍历结果。例如:
给定二叉树 {1,#,2,3}
1 \ 2 / 3
返回 [1,2,3]
注意:仅用递归解决是不够的,你能用迭代解决吗?
写完之后才发现Note里面要用迭代。。。不过这一问把我问得有点迷糊了,感觉自己写的应该是算递归的,但是怎么样才算迭代呢?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
if(!root) return ans;
traval(ans,root);
return ans;
}
void traval(vector<int>& ans,TreeNode* root){
ans.push_back(root->val);
if(root->left) traval(ans,root->left);
if(root->right) traval(ans,root->right);
}
};