描述:
给出一棵二叉树,返回其节点值的前序遍历。
样例:
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
思路:
递归函数。
AC代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> v;
void front(TreeNode *root)
{
if(root==NULL)
return;
else
{
v.push_back(root->val);
front(root->left);
front(root->right);
}
}
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
front(root);
return v;
}
};