查找二叉排序树的双亲节点,并输出路径
题目
设计算法查找二叉排序树中某特定值的双亲结点。如果找到,输出从根结点到该值结点的双亲结点的路径。找不到这样的结点或根结点就等于该特定值就返回一个未找到的提示。例如下图,查找17,就输9,18,16。查找19,就输出未找到。
算法思想
① 特定结点值等于当前节点值或者当前结点为空,返回空,表示未找到特定值。
若特定结点值不等于当前节点值,执行②。
② 如果特定结点不等于当前结点左孩子或者右孩子的值,输出当前结点值,
如果特定结点值小于当前结点值,将当前结点的左孩子作为参数递归调用本函数;
如果特定结点值大于当前结点值,将当前结点的右孩子作为参数递归调用本函数。
如果特定结点等于左孩子或者右孩子的值,返回左孩子或者右孩子,表示找到特定值。并且在递归过程中,已经输出了路径。
TreeNode* ParentPath(TreeNode* node,int x)
{
if(node == NULL || x == node->key)//如果特定值等于当前节点值或当前节点值为空,无双亲。
return NULL;
else{
printf("%d ",node->key);
if((node->lChild ==NULL || x != node->lChild->key)
&& (node->rChild ==NULL || x != node->rChild->key))
{
if (x < node->key) //与左孩子比较
ParentPath(node->lChild,x);
else if (x > node->key) //查看右孩子
ParentPath(node->rChild,x);
}
else if((node->lChild !=NULL && x == node->lChild->key)
|| (node->rChild !=NULL && x == node->rChild->key))
return node;
}
}
完整代码
代码project https://download.csdn.net/download/qq_42295590/17647245
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct TreeNode
{
int key;
struct TreeNode* lChild;
struct TreeNode* rChild;
}TreeNode;
void inDFS(TreeNode *node)
{
if(node != NULL) {
inDFS(node->lChild);
printf("%d ",node->key);
inDFS(node->rChild);
}
}
//写一个函数专门插入子孩子,采用递归,从根节点开始寻找合适的插入点
void BSTInsert(TreeNode *&node, int key)
{
if (NULL == node) //为空的位置即为插入位置
{
node = (TreeNode*)malloc(sizeof(TreeNode)); //申请并插入新结点
node->lChild = NULL;
node->rChild = NULL;
node->key = key;
}
else{
if (key < node->key) //与左孩子比较
BSTInsert(node->lChild,key);
else if (key > node->key) //查看右孩子
BSTInsert(node->rChild,key);
else
printf("\nThe node(%d) already exists.\n", key);
}
}
// 结点个数:6
// 结点值: 9 8 18 7 16 17
void CreateBST(TreeNode *&node)
{
int n,i=0,key;
printf("请输入二叉树结点个数 ");
scanf("%d",&n); //二叉树结点个数
printf("请输入二叉树结点值序列 ");
for(i=0;i<n;i++)
{
scanf("%d",&key); //输入结点值
BSTInsert(node,key);
}
}
TreeNode* ParentPath(TreeNode* node,int x)
{
if(node == NULL || x == node->key)//如果特定值等于当前节点值或当前节点值为空,无双亲。
return NULL;
else{
printf("%d ",node->key);
if((node->lChild ==NULL || x != node->lChild->key)
&& (node->rChild ==NULL || x != node->rChild->key))
{
if (x < node->key) //与左孩子比较
ParentPath(node->lChild,x);
else if (x > node->key) //查看右孩子
ParentPath(node->rChild,x);
}
else if((node->lChild !=NULL && x == node->lChild->key)
|| (node->rChild !=NULL && x == node->rChild->key))
return node;
}
}
int main()
{
TreeNode * root= NULL;
TreeNode * p= NULL;
CreateBST(root);
printf("\n中序遍历二叉排序树结构 ");
inDFS(root);
int x=0;
printf("\n输入特定值 ");
scanf("%d",&x);
printf("\n%d的双亲结点路径 ",x);
p=ParentPath(root,x);
if(p == NULL) printf("\n找不到%d的双亲结点\n",x);
else printf("\n%d的双亲为 %d",x,p->key);
return 0;
}