二叉树的非递归遍历完整代码
时间: 2024-05-10 18:12:20 浏览: 87
二叉树的非递归遍历
二叉树的非递归遍历可以使用栈来实现。以下是三种遍历方式的完整代码:
前序遍历:
```
void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
cout << node->val << " ";
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
}
```
中序遍历:
```
void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> st;
TreeNode* node = root;
while (node != NULL || !st.empty()) {
while (node != NULL) {
st.push(node);
node = node->left;
}
node = st.top();
st.pop();
cout << node->val << " ";
node = node->right;
}
}
```
后序遍历:
```
void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
stack<TreeNode*> st1, st2;
st1.push(root);
while (!st1.empty()) {
TreeNode* node = st1.top();
st1.pop();
st2.push(node);
if (node->left) st1.push(node->left);
if (node->right) st1.push(node->right);
}
while (!st2.empty()) {
TreeNode* node = st2.top();
st2.pop();
cout << node->val << " ";
}
}
```
阅读全文