网上的博客写得很好了,直接贴网址。
https://blog.csdn.net/gatieme/article/details/51163010
另外,wikipedia上也写得很详细:
https://zh.wikipedia.org/wiki/%E6%A0%91%E7%9A%84%E9%81%8D%E5%8E%86
一、Leetcode 144. 二叉树的前序遍历
/**
* 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> res;
fun(res,root);
return res;
}
void fun(vector<int> &res,TreeNode* root)
{
if(root==NULL) return;
res.push_back(root->val);
fun(res,root->left);
fun(res,root->right);
}
};
二、Leetcode 94. 二叉树的中序遍历
/**
* 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> res;
fun(root,res);
return res;
}
void fun(TreeNode* root, vector<int> &res)
{
if(root==NULL) return;
fun(root->left,res);
res.push_back(root->val);
fun(root->right,res);
}
};
三、Leetcode 145. 二叉树的后序遍历
/**
* 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> res;
fun(res,root);
return res;
}
void fun(vector<int> &res,TreeNode* root)
{
if(root==NULL) return;
fun(res,root->left);
fun(res,root->right);
res.push_back(root->val);
}
};