非递归中序遍历二叉树c
时间: 2023-05-21 12:05:25 浏览: 162
非递归中序遍历二叉树的代码如下:
void inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* curr = root;
while (curr != NULL || !s.empty()) {
while (curr != NULL) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
cout << curr->val << " ";
curr = curr->right;
}
}
其中,stack是用来存储节点的栈,curr是当前遍历到的节点。首先将根节点压入栈中,然后遍历其所有左子节点并依次压入栈中,直到没有左子节点为止。然后取出栈顶元素,输出其值,将curr指向其右子节点。重复上述过程,直到所有节点都被遍历完毕。
相关问题
c++实现非递归中序遍历二叉树
以下是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 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;
}
```
二叉树非递归中序遍历C语言实现
以下是二叉树非递归中序遍历的C语言实现:
```c
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义栈结构体
typedef struct Stack {
TreeNode** arr;
int top;
int maxSize;
} Stack;
// 创建栈
Stack* createStack(int size) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->arr = (TreeNode**)malloc(sizeof(TreeNode*) * size);
stack->top = -1;
stack->maxSize = size;
return stack;
}
// 入栈
void push(Stack* stack, TreeNode* node) {
if (stack->top == stack->maxSize - 1) {
return;
}
stack->arr[++stack->top] = node;
}
// 出栈
TreeNode* pop(Stack* stack) {
if (stack->top == -1) {
return NULL;
}
return stack->arr[stack->top--];
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 中序遍历
int* inorderTraversal(TreeNode* root, int* returnSize) {
*returnSize = 0;
int* res = (int*)malloc(sizeof(int));
Stack* stack = createStack(100); // 创建栈
TreeNode* cur = root;
while (cur != NULL || !isEmpty(stack)) {
while (cur != NULL) { // 遍历左子树并入栈
push(stack, cur);
cur = cur->left;
}
cur = pop(stack); // 左子树遍历完毕,出栈一个节点
res = (int*)realloc(res, sizeof(int) * (*returnSize + 1));
res[(*returnSize)++] = cur->val; // 将出栈节点的值加入结果数组
cur = cur->right; // 遍历右子树
}
return res;
}
```
该实现利用栈来模拟递归的过程,将待遍历的节点入栈,遍历完左子树后出栈一个节点,将其值加入结果数组,然后遍历其右子树。重复以上步骤直到栈为空。
阅读全文