试用C语言编写一个二叉树按层遍历和先序非递归遍历函数
时间: 2024-05-02 20:23:39 浏览: 88
二叉树按层遍历函数的代码如下:
```
void levelOrderTraversal(Node* root) {
if (root == NULL)
return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
q.pop();
cout << current->data << " ";
if (current->left != NULL)
q.push(current->left);
if (current->right != NULL)
q.push(current->right);
}
}
```
先序非递归遍历函数的代码如下:
```
void preOrderTraversal(Node* root) {
if (root == NULL)
return;
stack<Node*> s;
s.push(root);
while (!s.empty()) {
Node* current = s.top();
s.pop();
cout << current->data << " ";
if (current->right != NULL)
s.push(current->right);
if (current->left != NULL)
s.push(current->left);
}
}
```
请注意对以上代码进行适当测试,以验证其正确性。
阅读全文