样例
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,2,3].
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> vec;
first(vec,root);
return vec;
}
void first(vector<int> &vec,TreeNode *root){
if(root==NULL) return;
else
{
vec.push_back(root->val);
first(vec,root->left);
first(vec,root->right);
}
}
};
写一个递归函数,将每一次遍历的节点放在vector里,前序遍历完成后,将vector里的值输出即可利用数组输出