非递归实现树的前序遍历栈的代码C++
时间: 2023-05-29 14:03:17 浏览: 63
数据结构基于C++语言程序开发的树的非递归先序遍历
```
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
cout << node->val << " ";
if (node->right != NULL) {
s.push(node->right);
}
if (node->left != NULL) {
s.push(node->left);
}
}
}
```
阅读全文