问题描述:
给出一棵二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1
\
2
/
3
返回 [1,2,3].
解题思路:
在函数外重新定义一个前序遍历函数,在另一个函数中调用,在写前序遍历的函数时,可运用递归。
代码:
/**
* 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.
*/
void preorder(vector<int>&v,TreeNode *root){
if(root==NULL) return ;
v.push_back(root->val);
preorder(v,root->left);
preorder(v,root->right);
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> v;
preorder(v,root);
return v;
// write your code here
}
};
注意中序遍历函数中的引用