二叉树先序遍历代码c++
时间: 2023-07-09 08:03:39 浏览: 134
以下是二叉树先序遍历的 C++ 代码:
```c++
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
```
这里定义了一个二叉树节点的结构体 `TreeNode`,包含值 `val`、左子节点 `left` 和右子节点 `right`。`preorderTraversal` 函数实现了二叉树的先序遍历,先输出当前节点的值,再遍历左子树,最后遍历右子树。在遍历空节点时,直接返回。
相关问题
C++ 二叉树先序遍历代码
二叉树先序遍历的代码可以用递归和非递归方式实现,下面是用非递归方式实现的代码: ```
void PreorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
stack<TreeNode *> s;
s.push(root);
while (!s.empty()) {
TreeNode *tmp = s.top();
cout << tmp->val << endl;
s.pop();
if (tmp->right) {
s.push(tmp->right);
}
if (tmp->left) {
s.push(tmp->left);
}
}
}
```
二叉树先序遍历C++
在C++中,二叉树的先序遍历是一种常见的树遍历算法,按照“根-左-右”的顺序访问节点。以下是使用递归方式实现二叉树先序遍历的C++代码:
```cpp
// 假设我们有一个二叉树节点定义如下:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 先序遍历的递归函数
void preorderTraversal(TreeNode* root) {
if (root != nullptr) {
// 访问根节点
std::cout << root->val << " ";
// 递归遍历左子树
preorderTraversal(root->left);
// 递归遍历右子树
preorderTraversal(root->right);
}
}
```
在实际使用时,你可以将`TreeNode`结构体替换为你实际的二叉树节点定义,并调用`preorderTraversal`函数传入树的根节点开始遍历。
阅读全文
相关推荐











