二叉树的前序,中序,后序遍历
94. 二叉树的中序遍历
144. 二叉树的前序遍历
145. 二叉树的后序遍历
题意:
给你二叉树的根节点
root
,返回它节点值的 前序 ,中序,后序遍历。
解题思路:
二叉树的遍历,利用了递归,只是修改了压入数组的位置即可.
代码:
1.前序:
class Solution {
public:
void VLR(TreeNode *root, vector<int> &res)
{
if (root == nullptr)
return;
res.push_back(root->val);
VLR(root->left,res);
VLR(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
VLR(root, res);
return res;
}
};
2.中序:
class Solution {
public:
void LDR(TreeNode *root, vector<int> &res)
{
if (root == nullptr)
return;
LDR(root->left, res);
res.push_back(root->val);
LDR(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
LDR(root, res);
return res;
}
};
3.后序
class Solution {
public:
void LRD(TreeNode *root, vector<int> &res)
{
if (root == nullptr)
return;
LRD(root->left, res);
LRD(root->right, res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
LRD(root, res);
return res;
}
};
总结:
二叉树的递归遍历只需要理解啥时候压入数组和返回条件位空节点即可.