前序遍历
前序遍历首先访问根节点,然后遍历左子树,最后遍历右子树。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> a;
vector<int> res=real(root,a);
return res;
}
vector<int> real(TreeNode* root,vector<int> &a)
{
if(root==NULL)
{
return a;
}
//按照前序遍历的顺序,根左右
a.push_back(root->val);//根
real(root->left,a);//左
real(root->right,a);//右
return a;
}
};
中序遍历
中序遍历是先遍历左子树,然后访问根节点,然后遍历右子树。
通常来说,对于二叉搜索树,我们可以通过中序遍历得到一个递增的有序序列。 我们将在另一张卡片(数据结构介绍 – 二叉搜索树)中再次提及。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> a;
vector<int> res=real(root,a);
return res;
}
vector<int> real(TreeNode* root,vector<int> &a)
{
if(root==NULL)
{
return a;
}
real(root->left,a);
a.push_back(root->val);
real(root->right,a);
return a;
}
};
后序遍历
后序遍历是先遍历左子树,然后遍历右子树,最后访问树的根节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> a;
vector<int> res=real(root,a);
return res;
}
vector<int> real(TreeNode* root,vector<int> &a)
{
if(root==NULL)
{
return a;
}
real(root->left,a);
real(root->right,a);
a.push_back(root->val);
return a;
}
};