简体   繁体   English

具有多个子节点和左右两个节点的二叉搜索树

[英]Binary Search Tree with multiple child and two nodes pointing left and right

I want to make a binary tree like this as given in the image given below in C programming language. 我要像下面的C编程语言所示,制作一个像这样的二进制树。

Structure to make binary tree having two nodes is this - 使具有两个节点的二叉树的结构是这样的-

struct node {
    int data;
    struct node* left;
    struct node* right;
};

But for making a tree with multiple childs, structure needs to change every time, so is there any way to make a structure that changes every time? 但是,要使一个带有多个子代的树的结构每次都需要改变,那么有什么办法可以使结构每次都改变吗?

在此处输入图片说明

You can define a node like this: 您可以这样定义一个节点:

struct node
{
    int data;
    node *firstChild;
    node *nextSibling;
};

And then, 接着,

  1. First child is accessed this way: myNode->firstChild 通过以下方式访问第一个孩子: myNode-> firstChild

  2. Second child: myNode->firstChild->nextSibling 第二个孩子: myNode-> firstChild-> nextSibling

  3. Nth child: myNode->firstChild->nextSibling->...->nextSibling 第N个子节点myNode-> firstChild-> nextSibling-> ...-> nextSibling

This will involve null checks and iteration when going through child nodes. 遍历子节点时将涉及空检查和迭代。

In C, you cannot make a structure change dynamically. 在C中,您无法动态更改结构。 But what you want (variable number of children in each node) can be achieved in a slightly roundabout way. 但是,您想要的(每个节点中的子级数目可变)可以通过稍微回旋的方式来实现。 If you want to preserve the left and right nodes as separate entities from the other children, you could have a binary tree that contains a linked list for all additional children of that node: 如果要将左节点和右节点保留为与其他子节点分开的实体,则可以有一个二叉树,其中包含该节点所有其他子节点的链表:

struct TreeNode
{
    int data;
    ChildNode *firstChild;
    TreeNode *left;
    TreeNode *right;
};

struct ChildNode
{
    int data;
    ChildNode *next;
};

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

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