从二进制搜索树中打印级别和节点

时间:2019-04-10 21:14:21

标签: c binary-search-tree

我需要对二进制搜索树进行有序遍历,并且需要打印所有节点及其所在的级别,但是我想不出一种方法。

例如:

如果我有这个 bst,输出为:

4 #1
5 #0
9 #1
7 #2
10 #2
18 #3

到目前为止,这是我得到的:

这是我正在使用的结构:

struct tree {
    int number;
    tree *izq;
    tree *der;
};

typedef struct tree *bst;

这是我要实现的功能:

void printTree(bst node) {
    if (node==NULL) {
        return;
    }
    else {
        if (node->left != NULL) {
            printTree(node->left);
        }
        printf("%d", node->number);
        if (node->right !=NULL) {
            printTree(node->right);
        }
    }
}

有人有什么想法吗?谢谢:)

2 个答案:

答案 0 :(得分:1)

我使用Java实现了此功能,但我认为您可以轻松地将其转换为C:

private static void printWithLevels(TreeNode node) {
    printWithLevels(node, 0);
}

private static void printWithLevels(TreeNode node, int level) {
    if (node == null) return;

    System.out.println(node.value + "(" + level + ")");

    printWithLevels(node.left, level + 1);
    printWithLevels(node.right, level + 1);
}

为使我的解决方案更完整,这是我对TreeNode的简单/快速实现:

private static class TreeNode {
    int value;
    TreeNode left;
    TreeNode right;

    TreeNode(int value, TreeNode left, TreeNode right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

答案 1 :(得分:0)

警告

struct tree {
    int number;
    tree *izq;
    tree *der;
};

必须

struct tree {
    int number;
    struct tree *izq;
    struct tree *der;
};

因为在开始时检查了节点为NULL的情况,所以可以简化:

void printTree(bst node) {
    if (node != NULL) {
      printTree(node->izq);
      printf("%d", node->number);
      printTree(node->der);
    }
}

添加级别:

void printTree(bst node, int lvl) {
    if (node != NULL) {
      printTree(node->izq, lvl + 1);
      printf("%d #%d\n", node->number, lvl);
      printTree(node->der, lvl + 1);
    }
}

然后您在根级别调用0


制作完整的程序:

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

struct tree {
    int number;
    struct tree *izq;
    struct tree *der;
};

typedef struct tree *bst;

void printTree(bst node, int lvl) {
    if (node != NULL) {
      printTree(node->izq, lvl + 1);
      printf("%d #%d\n", node->number, lvl);
      printTree(node->der, lvl + 1);
    }
}

struct tree * mk(int v, struct tree * l, struct tree * r)
{
  struct tree * t = malloc(sizeof(struct tree));

  t->number = v;
  t->izq = l;
  t->der = r;

  return t;
}

int main()
{
  struct tree * r = mk(5, mk(4, NULL, NULL), mk(9, mk(7, NULL, NULL), mk(10, NULL, mk(18, NULL, NULL))));

  printTree(r, 0);
}

编译执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
4 #1
5 #0
7 #2
9 #1
10 #2
18 #3