先序输出第i个结点
时间: 2023-07-18 11:06:12 浏览: 49
如果是二叉树的先序遍历,可以按照以下步骤输出第i个结点:
1. 如果当前结点是空,返回。
2. 访问当前结点。
3. 如果已经访问了第i个结点,返回。
4. 递归遍历左子树,传入参数i。
5. 如果已经访问了第i个结点,返回。
6. 递归遍历右子树,传入参数i。
下面是一个示例代码:
```
void preOrder(TreeNode* root, int& i, TreeNode*& result) {
if (!root) return;
if (++i == k) {
result = root;
return;
}
preOrder(root->left, i, result);
if (result) return;
preOrder(root->right, i, result);
}
TreeNode* findKthNode(TreeNode* root, int k) {
int i = 0;
TreeNode* result = nullptr;
preOrder(root, i, result);
return result;
}
```
在这个示例代码中,我们定义了一个`preOrder`函数来进行先序遍历。其中,`i`表示当前遍历到第几个结点,`result`表示已经找到的第`k`个结点。
最后,我们调用`findKthNode`函数,传入根结点和要查找的结点编号`k`,即可找到第`k`个结点。
相关问题
void PrintNode(BiTree T)用这个函数名写一个先序输出第i个结点递归
以下是用函数名 PrintNode 实现先序输出第 i 个结点递归的代码:
```
void PrintNode(BiTree T, int i, int &count) {
if (T) {
count++;
if (count == i) {
printf("%c ", T->data);
return;
}
PrintNode(T->lchild, i, count);
PrintNode(T->rchild, i, count);
}
}
```
其中,BiTree 是二叉树的结构体类型,count 是用来记录当前遍历到的结点序号的变量。在调用 PrintNode 函数时,需要传入二叉树的根节点 T,要输出的结点序号 i,以及计数器变量 count 的地址 &count。在函数内部,先将计数器 count 加 1,表示当前遍历到了一个结点。如果计数器 count 等于要输出的结点序号 i,就输出该结点的数据,并直接返回。否则,继续递归遍历该结点的左右子树。
void PrintNode(BiTree T)用这个函数名写一个先序输出第i个结点
这里给出一个示例代码,其中使用了一个全局计数器变量 count 来记录当前是第几个节点:
```
int count = 1; // 全局计数器
void PrintNode(BiTree T, int i) {
if (T == NULL) {
return;
}
if (count == i) { // 如果当前节点是第 i 个节点,则输出该节点的值
printf("%c\n", T->data);
return;
}
count++; // 继续遍历左子树
PrintNode(T->lchild, i);
count++; // 继续遍历右子树
PrintNode(T->rchild, i);
}
```
调用方式:
```
PrintNode(T, i); // T 为二叉树的根节点指针,i 为要输出的节点的序号
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)