先序遍历
https://leetcode.cn/problems/binary-tree-preorder-traversal/description/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void preorder(TreeNode *root, vector<int> &res)
{
if(root == nullptr)
{
return;
}
else
{
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
}
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
// 必须新起一个函数,否则每次都会重新定义vector
preorder(root, res);
return res;
}
};
中序遍历
https://leetcode.cn/problems/binary-tree-inorder-traversal/description/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void inorder(TreeNode *root, vector<int> &res)
{
if(root == nullptr)
{
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root)
{
// 中序遍历默认树已经存在,不需要判空
vector<int> res;
inorder(root, res);
return res;
}
};
后序遍历
https://leetcode.cn/problems/binary-tree-postorder-traversal/description/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void postorder(TreeNode *root, vector<int> &res)
{
if(root == nullptr)
{
return;
}
postorder(root->left, res);
postorder(root->right, res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> res;
postorder(root, res);
return res;
}
};