如何用c++非递归中序遍历二叉树
时间: 2023-11-20 12:08:00 浏览: 100
以下是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;
}
```
阅读全文