posts - 137,comments - 0,views - 40818
复制代码
#include <vector>
#include <iostream>
#include <string>
using namespace std;
//二叉树的定义
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int a) :val(a), left(NULL), right(NULL) {}
};
//使用递归进行前序遍历
void preoder(TreeNode* cur, std::vector<int>& ret) {
  ret.push_back(cur->val);
  preoder(cur->left, ret);
  preoder(cur->right, ret);
}
//使用递归进行中序遍历
void inoder(TreeNode* cur, std::vector<int>& ret) {
  inoder(cur->left, ret);
  ret.push_back(cur->val);
  inoder(cur->right, ret);
}
//使用递归进行后序遍历
void backoder(TreeNode* cur, std::vector<int>& ret) {
  preoder(cur->left, ret);
  preoder(cur->right, ret);
  ret.push_back(cur->val);
}
//使用栈进行前序遍历
vector<int> preoder1(TreeNode* root) {
  stack<TreeNode*> s;
  vector<int> ret;//存放已经遍历好的数组
  if (!root) {
    return ret;
  }
  s.push(root);
  while (!s.empty()) {
    TreeNode* tmp = s.top();
    s.pop();
    ret.push_back(tmp->val);
    if (tmp->right) {
      s.push(tmp->right);
    }
    if (tmp->left) {
      s.push(tmp->left);
    }
  }
  return ret;
}
//使用栈进行后序遍历
vector<int> postorder(TreeNode* root) {
  vector<int> tmp;
  if (!root) return tmp;
  stack<TreeNode*> s;
  s.push(root);
  while (!s.empty()) {
    TreeNode* node = s.top();
    s.pop();
    tmp.push_back(node->val);
    if (node->left) s.push(node->left);
    if (node->right) s.push(node->right);
  }
  reverse(tmp.rbegin(), tmp.rend());
  return tmp;
}
//使用栈进行中序遍历
vector<int> inorder2(TreeNode* root) {
  vector<int> tmp;
  if (!root) return tmp;
  TreeNode* cur = root;
  stack<TreeNode*> s;
  while (cur || !s.empty()) {
    if (cur) {
      s.push(cur);
      cur = cur->left;
    }
    else {
      cur = s.top();
      s.pop();
      tmp.push_back(cur->val);
      cur = cur->right;
    }
  }
  return tmp;
}
复制代码

 

posted on   wshidaboss  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
历史上的今天:
2023-03-06 C/C++ 数据结构栈的应用-迷宫的求解
2023-03-06 C/C++ 数据结构链栈的基本操作实现
2023-03-06 C/C++ 数据结构堆排序算法的实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示