二叉树的非递归遍历c++
时间: 2023-12-06 11:56:03 浏览: 80
以下是二叉树的非递归遍历C语言代码:
1. 非递归先序遍历
```
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
printf("%d ", node->val);
if (node->right) {
s.push(node->right);
}
if (node->left) {
s.push(node->left);
}
}
}
```
2. 非递归中序遍历
```
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
TreeNode* node = root;
while (!s.empty() || node != NULL) {
if (node != NULL) {
s.push(node);
node = node->left;
} else {
node = s.top();
s.pop();
printf("%d ", node->val);
node = node->right;
}
}
}
```
3. 非递归后序遍历
```
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
s.push(root);
TreeNode* pre = NULL;
while (!s.empty()) {
TreeNode* node = s.top();
if ((node->left == NULL && node->right == NULL) || (pre != NULL && (pre == node->left || pre == node->right))) {
printf("%d ", node->val);
s.pop();
pre = node;
} else {
if (node->right != NULL) {
s.push(node->right);
}
if (node->left != NULL) {
s.push(node->left);
}
}
}
}
```
阅读全文