144. 二叉树的前序遍历
94. 二叉树的中序遍历
145. 二叉树的后序遍历
文章:代码随想录 (programmercarl.com)
视频:每次写递归都要靠直觉? 这次带你学透二叉树的递归遍历!| LeetCode:144.前序遍历,145.后序遍历,94.中序遍历_哔哩哔哩_bilibili
//前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result; //存放遍历结果的数组
traversal(root, result); //传入根节点和存放遍历结果的数组
return result;
}
void traversal(TreeNode* cur, vector<int>& vec)
{
if (cur == NULL)
{
return;
}
vec.push_back(cur->val);//中
traversal(cur->left, vec);//左
traversal(cur->right, vec);//右
}
};
//中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result; //存放遍历结果的数组
traversal(root, result);
return result;
}
void traversal(TreeNode* cur, vector<int>& vec)
{
if(cur == NULL)
{
return;
}
//左中右
traversal(cur->left, vec);//左
vec.push_back(cur->val);//中
traversal(cur->right, vec);//右
}
};
//后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result; //存放遍历结果的数组
traversal(root, result);
return result;
}
//左右中
void traversal(TreeNode* cur, vector<int>& vec)
{
if (cur == NULL)
{
return;
}
traversal(cur->left, vec); //左
traversal(cur->right, vec); //右
vec.push_back(cur->val); //中
}
};
标签:result,遍历,cur,随想录,traversal,vector,vec,14,二叉树
From: https://www.cnblogs.com/chaoyue-400/p/17067448.html