简体   繁体   English

二叉搜索树遍历

[英]Binary search tree traversal

Hi guys I have a doubt in inserting a new node in BST.大家好,我对在 BST 中插入新节点有疑问。 In the addNode module I am trying to insert an element in the BST, but each time while adding a new node it is adding to the same root node which I passed from main function initially without traversing inside the tree.addNode模块中,我试图在 BST 中插入一个元素,但是每次添加新节点时,它都会添加到我最初从main函数传递的同一个根节点,而没有在树内部遍历。

This is the code which I have written.这是我写的代码。

#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<iostream>
using namespace std;
struct node
{
    int data;
    struct node *left;
    struct node *right;
};
struct node* newNode(int data)
{
    node* temp = (node*)malloc(sizeof(struct node));
    //struct temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return(temp);
};
int addNode(node *dest, node *root)
{
    if(root == NULL)
    {
        cout<<"adding data to node for "<< dest->data<<endl;
        root = dest;
        cout<<"ROOT VALUE = root->data "<<root->data<<endl;
        return 1;
    }
    if(dest->data > root->data)
    {
        cout<<"Traverse right for "<<dest->data<<endl;
        addNode(dest, root->right);
    }
    else if(dest->data < root->data)
    {
        cout<<"Traverse left for "<<dest->data<<endl;
        addNode(dest, root->left);
    }
}
void printNodes(node *root)
{
    if(root != NULL)
    {
        printNodes(root->left);
        if(root->left != NULL && root->right != NULL)
            std::cout<< root->data <<" ";
        printNodes(root->right);
    }
}
int main()
{
    int i, j, k, flag;
    int arr[6] = {4, 2,8, 1, 0, 10};
    node *start = newNode(arr[0]);
    for(i = 1; i < 6; i++)
    {
        node *newOne = newNode(0);
        newOne->data = arr[i];
        cout<<"NODE DATA - start->data "<<start->data;
        if(addNode(newOne, start))
            std::cout<<"\nNode added"<<endl;
    }
    printNodes(start);
    return 1;
}

I am quite new to trees concept as well as pointers concept in trees.我对树的概念以及树中的指针概念很陌生。 Any help is appreciated and thank you.感谢您提供任何帮助。

... but each time while adding a new node it is adding to the same root node ...但每次添加新节点时,它都会添加到同一个根节点

This is because you are adding it always to the same root, as here这是因为您总是将它添加到同一个根目录,如下所示

if(addNode(newOne, start))

start is always the same. start总是一样的。 You could make addNode return the new root and call it like that:你可以让addNode返回新的根并像这样调用它:

start = addNode(newOne,start);

I'll leave it to you to implement it.我会让你来实施它。

Note that parameters are always passed by value in c++ (unless you pass-by-reference), thus changing the parameter inside the method, root = dest;注意参数在c++中总是按值传递的(除非你是按引用传递的),从而改变了方法内部的参数, root = dest; , has no effect on the start in main . , 对mainstart没有影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM