144.二叉树的中序遍历
145.二叉树的后序遍历
94.二叉树的中序遍历
首先,要理解递归函数的方法
(1)确定单层逻辑
(2)确定终止条件
(3)确定函数成员变量与输出变量
第二个好理解,当左边树节点和右边树节点都为空时,既可以截断输出
参考代码随想录的代码,我的代码如下
// 二叉树的遍历.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<vector>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) :val(x), left(nullptr), right(nullptr) {}
};
//初始化二叉树
//void createBinarytree(TreeNode*&root,int &val) {
// vector<int>nums = {1,3,5,7,9,2,4};
// for (auto val : nums) {
// if (root == nullptr) {
// root = new TreeNode(val);
// }
// if (val < root->val) {
// createBinarytree(root->left, val);
// }
// else {
// createBinarytree(root->right, val);
// }
// }
//}
class Solution {
public:
TreeNode* root;
//定义递归函数
//中序遍历
void travsalLMF(TreeNode* cur, vector<int>vec) {
if (cur == nullptr) return;
vec.push_back(cur->val);
if (cur->left != nullptr) {
travsalLMF(cur->left,vec);
}
if (cur->right != nullptr) {
travsalLMF(cur->right, vec);
}
}
//前序遍历
void travsalMLF(TreeNode* cur, vector<int>vec) {
if (cur == nullptr) return;
if (cur->left != nullptr) {
travsalMLF(cur->left, vec);
}
vec.push_back(cur->val);
if (cur->right != nullptr) {
travsalMLF(cur->right, vec);
}
}
//后序遍历
void travsalLFM(TreeNode* cur, vector<int>vec) {
if (cur == nullptr) return;
if (cur->right != nullptr) {
travsalLFM(cur->right, vec);
}
vec.push_back(cur->val);
if (cur->left != nullptr) {
travsalLFM(cur->left, vec);
}
}
向二叉树根部插入元素
//void insert(int val) {
// insert(root, val);
//}
向二叉树插入元素
//void insert(TreeNode*& node, int val) {
// if (node == nullptr) {
// node = new TreeNode(val);
// return;
// }
// if (val < node->val) {
// insert(node->left, val);
// }
// else {
// insert(node->right, val);
// }
//}
遍历输出根部元素
//void print() {
// print(root);
//}
遍历输出二叉树
//void print(TreeNode* node) {
// if (node == nullptr) return;
// print(node->left);
// std::cout << node->val << " ";
// print(node->right);
//}
vector<int>Ergonic(TreeNode* &root) {
vector<int>result;
travsalLFM(root, result);
return result;
}
};
void insert(TreeNode*& root, int val) {
if (root == nullptr) { // 如果当前节点为空,则将元素插入到当前位置
root = new TreeNode(val);
return;
}
if (val < root->val) { // 如果待插入的元素小于当前节点的值,继续向左子树递归
insert(root->left, val);
}
else { // 否则,继续向右子树递归
insert(root->right, val);
}
}
int main()
{
Solution s;
TreeNode* root = new TreeNode(10);
insert(root, 6);
insert(root, 15);
insert(root, 3);
insert(root, 8);
insert(root, 12);
insert(root, 17);
vector<int>result = s.Ergonic(root);
for (auto val:result) {
cout << val << " ";
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
今天着实忙,一共学习2小时