Binary Tree Iterative Traversal

本文介绍了二叉树的三种遍历方式:前序遍历、中序遍历及后序遍历,并提供了详细的C++实现代码。每种遍历方式都通过栈来辅助完成,确保了遍历过程的正确性和高效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Preorder

 

 1 class Solution {
 2 public:
 3     vector<int> preorderTraversal(TreeNode* root) {
 4         vector<int> res;
 5         if (!root) return res;
 6         stack<TreeNode *> sta;
 7         sta.push(root);
 8         while (!sta.empty())
 9         {
10             TreeNode* cur = sta.top();
11             sta.pop();
12             res.push_back(cur->val);
13             if (cur->right) sta.push(cur->right);
14             if (cur->left) sta.push(cur->left);
15         }
16         return res;
17     }
18 };

 

 

postorder

 

 1 class Solution {
 2 public:
 3     vector<int> postorderTraversal(TreeNode* root) {
 4         vector<int> res;
 5         if (!root) return res;
 6         stack<TreeNode *> sta;
 7         sta.push(root);
 8         TreeNode *last = NULL;
 9         while (!sta.empty())
10         {
11             TreeNode *cur = sta.top();
12             TreeNode *left = cur->left, *right = cur->right;
13             if (left && (!last || (last != left && last != right)))
14                 sta.push(left);
15             else if (right && (!last || last != right))
16                 sta.push(right);
17             else
18             {
19                 res.push_back(cur->val);
20                 last = cur;
21                 sta.pop();
22             }
23         }
24         return res;
25     }
26 };

 

 

 

inorder

 

 1 class Solution {
 2 public:
 3     vector<int> inorderTraversal(TreeNode* root) {
 4         vector<int> res;
 5         stack<TreeNode*> sta;
 6         while(1) {
 7             while(root) { sta.push(root); root = root->left; }
 8             if(sta.empty()) break;
 9             root = sta.top(); sta.pop();
10             res.push_back(root->val);
11             root = root->right;
12         }
13         return res;
14     }
15 };

 

 

 

  

转载于:https://www.cnblogs.com/fenshen371/p/5168073.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值