简体   繁体   English

如何为二进制搜索树比较两个字符串

[英]How to compare two strings for a binary search tree

I am trying to compare two strings to see where it should go as a leaf node from the root and so fourth. 我正在尝试比较两个字符串,以查看它应该作为根节点的叶节点(第四个)。 I keep trying to use string compare and I get an error. 我一直尝试使用字符串比较,但出现错误。 I am very unfamiliar with binary trees in c and need help inserting nodes. 我对c中的二叉树不熟悉,需要插入节点的帮助。

Here is the code I have so far that is giving me an error: 这是我到目前为止给我一个错误的代码:

#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 15

typedef struct treeNode{
  char string[MAXLEN+1];
  struct treeNode *left;
  struct treNode *right;
}treeNode;

treeNode * insert(treeNode *node, char s[MAXLEN+1]){
  if(node == NULL){
    treeNode *temp;
    temp = (treeNode *)malloc(sizeof(treeNode));
    strncpy(temp -> string, s, sizeof(treeNode));
    temp -> left = NULL;
    temp -> right = NULL;
    return temp;
  }

  else-if(strcmp(node->string,char s)>0){

  }
}

There are three problems in your program right now: 您的程序中目前存在三个问题:

  1. "else-if" should be "else if" “ else-if”应为“ else if”

  2. strcmp(node->string,char s) should be strcmp(node->string, s) strcmp(node-> string,char s)应该是strcmp(node-> string,s)

  3. No main method 没有主要方法

First I think you should change 首先,我认为你应该改变

strcmp(node->string,char s);

And replace it with 并替换为

strcmp(node->string,s);

In strcmp if the result is greater than zero then the first argument is greater than the second. 在strcmp中,如果结果大于零,则第一个参数大于第二个参数。

So if your if else statement evaluates true then node->string is greater than s. 因此,如果您的if else语句评估为true,则node-> string大于s。

And if strcmp is less than zero then the second argument is greater than the first value. 如果strcmp小于零,则第二个参数大于第一个值。

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

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