c++非递归深度优先遍历代码
时间: 2023-07-24 14:11:59 浏览: 103
下面是C++实现非递归深度优先遍历的代码:
```c++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// 定义节点结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
vector<int> dfs(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* cur = s.top();
s.pop();
res.push_back(cur->val);
if (cur->right) {
s.push(cur->right);
}
if (cur->left) {
s.push(cur->left);
}
}
return res;
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
vector<int> res = dfs(root);
for (auto val : res) {
cout << val << " ";
}
return 0;
}
```
这里我们使用了一个栈来保存节点,从而实现了非递归的深度优先遍历。具体的实现细节可以参考代码中的注释。
阅读全文