二叉树后序遍历的非递归算法的c++代码
时间: 2023-12-01 14:58:22 浏览: 83
下面是二叉树后序遍历的非递归算法的 C++ 代码:
```c++
#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 postorderTraversal(TreeNode* root) {
if (!root) return;
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* cur = s1.top();
s1.pop();
s2.push(cur);
if (cur->left) s1.push(cur->left);
if (cur->right) s1.push(cur->right);
}
while (!s2.empty()) {
cout << s2.top()->val << " ";
s2.pop();
}
}
int main() {
// create a binary tree
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
// postorder traversal
cout << "Postorder Traversal: ";
postorderTraversal(root);
return 0;
}
```
这里采用两个栈的方法,第一个栈 s1 用于遍历二叉树,每次遍历到一个节点,将其入栈 s2,并将其左右子节点入栈 s1。当 s1 为空时,遍历结束,最后按照 s2 的顺序输出节点值即可。
阅读全文