二叉树的前序遍历与中序遍历,使用递归实现。
前序遍历:
/**
* 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: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> x;
vector<int> preorderTraversal(TreeNode * root) {
// write your code here
if(root == NULL)
{
//x.push_back(root->val);
return x;
}
x.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return x;
}
};
中序遍历:
/**
* 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: A Tree
* @return: Inorder in ArrayList which contains node values.
*/
vector<int> x;
vector<int> inorderTraversal(TreeNode * root) {
// write your code here
if(root == NULL)
{
return x;
}
inorderTraversal(root->left);
x.push_back(root->val);
inorderTraversal(root->right);
return x;
}
};