中序非递归遍历二叉树C++
时间: 2023-12-01 22:40:52 浏览: 90
c++实现二叉树的4种遍历(递归和非递归)(csdn)————程序.pdf
以下是C++中实现二叉树的中序非递归遍历的代码:
```cpp
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* cur = root;
while (cur != NULL || !s.empty()) {
while (cur != NULL) {
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
cout << cur->val << " ";
cur = cur->right;
}
}
int main() {
TreeNode* root = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
inorderTraversal(root); // 输出:1 3 2
return 0;
}
```
阅读全文