void findkvalue(bitree t, int k, int& count) {
if (t != NULL){
count++;
if (count == k) {
cout << t->data << " "; // 输出第 k 个节点的值
return;
}
else{
findkvalue(t->lchild, k, count);
findkvalue(t->rchild, k, count);
}
}
}
注意后面这个else加不加都行;
完整代码
#include <iostream>
using namespace std;
// 二叉树节点结构
struct TreeNode {
int data; // 节点数据
struct TreeNode* lchild; // 左子节点指针
struct TreeNode* rchild; // 右子节点指针
};
typedef struct TreeNode* bitree; // 定义二叉树指针类型
void findkvalue(bitree t, int k, int& count) {
if (t != NULL){
count++;
if (count == k) {
cout << t->data << " "; // 输出第 k 个节点的值
return;
}
else{
findkvalue(t->lchild, k, count);
findkvalue(t->rchild, k, count);
}
}
}
bitree createNode(int data) {
bitree newNode = new TreeNode;
newNode->data = data;
newNode->lchild = NULL;
newNode->rchild = NULL;
return newNode;
}
bitree createBinaryTree() {
bitree root = createNode(1);
root->lchild = createNode(2);
root->rchild = createNode(3);
//root->lchild->lchild = createNode(4);
//root->lchild->rchild = createNode(5);
//root->rchild->lchild = createNode(6);
//root->rchild->rchild = createNode(7);
return root;
}
int main() {
// 创建二叉树
bitree root = createBinaryTree();
int k = 3; // 第 k 个节点
int count = 0; // 计数器
cout << "第 " << k << " 个节点的值为:";
findkvalue(root, k, count);
cout << endl;
return 0;
}