求二叉树先序序列中的第K(K>=1)个节点的值
#include <iostream>
#include "createTree.h"
using namespace std;
BTNode* findK(BTNode* bt,int x)//递归
{
BTNode* l = NULL, * r = NULL;
static int k = x;//静态变量,只初始化一次
if (bt == NULL)
return NULL;
else
{
k--;
if (k != 0)
{
l = findK(bt->lchild, k);
r = findK(bt->rchild, k);
}
else
return bt;
}
return l ? l : r;
}
char valueK(BTNode* bt, int k)//输出结果
{
return findK(bt, int k)->data;
}
int main()
{
Btree root = createTree();
int k = 4;
cout << valueK(root, k);
return 0;
}