c++ 二叉树中搜索节点
伊谢尔伦
伊谢尔伦 2017-04-17 13:50:15
0
2
911

创建了一个二叉树,希望搜索到给定info值的节点

以下为二叉树的相关结构类型定义:

#include "stdio.h"
#include"stdlib.h"
#include "iostream"
using namespace std;
typedef char ELEMTYPE;

#define number 20;
struct BinTreeNode;
typedef struct BinTreeNode* PBinTreeNode;
struct BinTreeNode
{
    ELEMTYPE info;
    PBinTreeNode lchild;
    PBinTreeNode rchild;
};
typedef struct BinTreeNode* PLNBinTree;

以下为创建二叉树算法:
root为已创建好的BinTreeNode类型节点,然后输入一个字符测试是否左子树/右子树为空,不为空则创建左子树/右子树

void constructBinTree(PLNBinTree root)//先根递归创建二叉树
{
    if (root == NULL)
        return;

    char temp = '0';
    cout << "输入左值";
    cin >> temp;
    if (temp == '#')
    {
        root->lchild = NULL;
        
    }
    else
    {
        root->lchild = new BinTreeNode;
        
        root->lchild->info = temp;
        
    }



    cout << "输入右值";
    cin >> temp;
    if (temp == '#')
    {
        root->rchild = NULL;
        
    }
    else
    {
        root->rchild = new BinTreeNode;
        
        root->rchild->info = temp;
        
    }
    constructBinTree(root->lchild);
    constructBinTree(root->rchild);

}

以下为搜索算法:
PBinTreeNode find(PLNBinTree root, char x)//寻找x所在位置
{

if (root == NULL)
    return 0;

if (root->info == x)
{
    return root;
 }
else return 0;
PBinTreeNode c;
c =  find(root->lchild, x);
if(!c)
    find(root->rchild, x);
return c;

}

以下为测试时结果:


找不出问题所在,求各位会的指教。谢谢!

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
刘奇

The parameters of constructBinTree() must be passed by reference. If you pass it by value, there must be a problem. root->lchild = new BinTreeNode;This sentence only gives a new object to the left child of a temporary variable root, but the outer object represented by root The layer pointer has no left child! The formal parameter root and the actual parameter point to two different memory areas. Got it?

迷茫

https://github.com/bloomsource/rbtree

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template