从节点打印值

时间:2014-04-09 17:20:20

标签: c struct nodes

我正在尝试查看“位字符串”,它将方向指向二叉树。我遇到的问题是当节点到达结尾时从节点打印值(null)然后返回到顶部,直到最后点击“位串”中的某个字符。

所以字符串:

char * directions = "RRLRRLRLLRLRRS";

将从根开始然后右转>右>左>右(假设点击一个假)然后它将返回到根并且向右移动> left> right> left> left(然后切换回到每次找到一个叶子时都会生根,一旦它到达“S”,它就会停止遍历。

我现在的代码现在正在尝试从最终命中的节点获取值以进行调试,并且它不会打印任何内容。如何解决这个问题?

(顺序只是帮助确定它在树中的位置)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
  int order;
  char value;
  struct Node * left;
  struct Node * right;
} Node;

Node * insert(Node * node, char value, int order){
  if(node == NULL){
    node = (Node *)malloc(sizeof(Node));
    node->value = value;
    node->order = order;
    node->left = NULL;
    node->right = NULL;
    return node;
  }
  if(order > node->order){
    node->right = insert(node->right, value, order);
  }
  else if(order < node->order){
    node->left = insert(node->left, value, order);
  }
  else {
    return;
  }
  return node;
}

int main(){


  Node * root = NULL;
  char * directions = "RRLRRLRLLRLRRS";
  int length = (int)strlen(directions);
  int i;

  root = insert(root, -1, 6);
  root = insert(root, -1, 4);
  root = insert(root, -1, 2);
  root = insert(root, 32, 1);
  root = insert(root, 114, 3);
  root = insert(root, 108, 5);
  root = insert(root, -1, 12);
  root = insert(root, -1, 8);
  root = insert(root, 111, 7);
  root = insert(root, -1, 10);
  root = insert(root, 101, 9);


  /* basics to see values at this point */
  i = 0;
  while(directions[i] != 'S'){
    if(directions[i] == 'L'){
      printf(root->value);
      root = root->left;
    }
    else if(directions[i] == 'R'){
      printf(root->value);
      root = root->right;     
    }
    i++;
  }

  return 0
}

1 个答案:

答案 0 :(得分:0)

如果我尝试按原样运行代码,则代码会出现故障,因为您没有&#34;重置&#34;击中叶节点后的根。我修改了你的printf语句,打印出Node结构的实际int字段,并添加了一个if-else来测试遍历中的当前节点是否为叶子:

  ...

  Node * origRoot = root;

  i = 0;
  while(directions[i] != 'S'){
    if(directions[i] == 'L'){
      printf("%d\n", root->order);
      if(root->left == NULL)
        root = origRoot;   
      else      
        root = root->left;
    }
    else if(directions[i] == 'R'){
      printf("%d\n", root->order);
      if(root->right == NULL)
        root = origRoot;   
      else      
        root = root->right;           
    }
    i++;
  }

  ...

我提供了一个可视化,并在此处逐步完成代码:gist.github.com/liangricha/10337524