二叉树的遍历
二叉树的遍历方式可分为三种:前序遍历、中序遍历、后序遍历
。使用递归
的方法对树进行遍历非常简单,使用迭代
的方式对树2进行遍历能够拥有更深的理解。
这里给出二叉树
的常用结构:
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) {}
};
一、前序遍历
1.递归
// 递归
void travel(struct TreeNode* root, int* arr, int* size) {
if (root != NULL) {
arr[(*size)++] = root->val;
travel(root->left, arr, size);
travel(root->right, arr, size);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* arr = (int*)malloc(100*sizeof(int));
*returnSize = 0;
travel(root, arr, returnSize);
return arr;
}
2.迭代
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(root == nullptr){
return vector<int>(0);
}
queue<int> q;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
TreeNode *fro = sta.top();
q.push(fro->val);
sta.pop();
if(fro->right!=nullptr){
sta.push(fro->right);
}
if(fro->left!=nullptr){
sta.push(fro->left);
}
}
vector<int> res(q.size(), 0);
int s = q.size();
for(int i = 0;i < s;i++){
res[i] = q.front();
q.pop();
}
return res;
}
};
二、中序遍历
1.递归
void travel(struct TreeNode* root, int* arr, int* size) {
if (root != NULL) {
travel(root->left, arr, size);
arr[(*size)++] = root->val;
travel(root->right, arr, size);
}
}
int* Traversal(struct TreeNode* root, int* returnSize){
int* arr = (int*)malloc(100*sizeof(int));
*returnSize = 0;
travel(root, arr, returnSize);
return arr;
}
2.迭代
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(root == nullptr){
return vector<int>(0);
}
vector<int> res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
// 先一直找左子树,直到找到最后一个
// root 是当前子树的根节点
while(root->left!=nullptr){
TreeNode *r = root;
sta.push(root->left);
root = root->left;
r->left = nullptr;
}
res.push_back(sta.top()->val);
sta.pop();
// 左子树找到低,开始寻找右子树
if(root->right!=nullptr){
root = root->right;
sta.push(root);
}else if(!sta.empty()){
root = sta.top();
}
}
return res;
}
};
三、后序遍历
1.递归
void travel(struct TreeNode* root, int* arr, int* size) {
if (root != NULL) {
travel(root->left, arr, size);
travel(root->right, arr, size);
arr[(*size)++] = root->val;
}
}
int* Traversal(struct TreeNode* root, int* returnSize){
int* arr = (int*)malloc(100*sizeof(int));
*returnSize = 0;
travel(root, arr, returnSize);
return arr;
}
2.迭代
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root == nullptr){
return vector<int>(0);
}
vector<int> res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
// 先找到最左边的子树
while(root->left){
TreeNode *r = root;
sta.push(root->left);
root = root->left;
r->left = nullptr;
}
// 左-右-根
// 再找到左子树的右子树(如果有的话)
if(root->right!=nullptr){
TreeNode *r = root;
root = root->right;
sta.push(root);
r->right = nullptr;
}else{
// 该节点的左右子树都为空 此时再将该节点输出
res.push_back(root->val);
sta.pop();
if(!sta.empty()){
root = sta.top();
}
}
}
return res;
}
};
致谢
感谢观看与点赞