二叉树遍历的递归写法:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x), left(NULL), right(NULL) {}
};
// 先序遍历
void preOrder(TreeNode* root)
{
if(root == NULL)
return;
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root)
{
if(root == NULL)
return;
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历
void lastOrder(TreeNode* root)
{
if(root == NULL)
return;
lastOrder(root->left);
lastOrder(root->right);
cout << root->val << " ";
}
#include <iostream>
#include <vec