【资料结构】树_实作-二元树的前中後追踪&&最大最小值&树叶

tree-二元树的前中後追踪&&最大最小值&树叶

实作练习

说明

实习课的一个作业,混合了前中後序的追踪,找最大最小值,找树叶点。

有时间再一个一个分开。

函式

get_max_min:将每一次新增的值带入,找出最大最小值

void get_max_min(int *max, int *min, int num) {
  if (*max < num) {
    *max = num;
  }
  if (*min > num) {
    *min = num;
  }
}

add_node:新增新的节点

tree_p add_node(int word) {
  tree_p add = (tree_p)malloc(sizeof(tree));
  add->data = word;
  add->left = NULL;
  add->right = NULL;
  return add;
}
呼叫这个函式时,会利用malloc产生一个节点空间,并利用存值,最後再回传。

seach:利用走访的方式寻找无延伸分支的节点

void seach(tree_p root) {
  if (root != NULL) {
    if (root->left == NULL && root->right == NULL) {
      printf("%d ", root->data);
    }
    //printf("(%d)", root->data);
    seach(root->left);
    seach(root->right);
  }
}
这边是利用中序追踪的方法,找出树叶点(两个分支皆为空)

show:show出来

void show(tree_p root, int max, int min) {
  printf("\n--------------------------------------\n");
  printf("\nPreorder  :");
  preorder(root);
  printf("\nInorder   :");
  inorder(root);
  printf("\npostorder :");
  postorder(root);
  printf("\nMAX:%d\n", max);
  printf("MIN:%d\n", min);
  printf("LeafNodes :");
  seach(root);
}

程序码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree *tree_p;
struct tree {
  int data;
  tree_p left;
  tree_p right;
} tree;

tree_p root;
tree_p ptr = root;
tree_p cur = ptr;
//相关结构与全域

int main() {
  int t = 0, num, max = 0, min = 100;
  while (1) {
    ptr = root;
    printf("Insert a number :");
    scanf("%d", &num);
    //基本输入
    if (num == 0) {
      break;
    }
    //当输入值为0时跳脱回圈
    get_max_min(&max, &min, num);
    //每一次输入後代入函式,判断是否是最大最小
    if (root == NULL) {
      root = add_node(num);
    } else {
      while (ptr != NULL) {
        cur = ptr;
        if (ptr->data > num) {
          ptr = ptr->left;
        } else if (ptr->data < num) {
          ptr = ptr->right;
        } else {
          printf("\nalready exit.\n");
          break;
        }
      }
      //当节点没碰到空白时,会一直往下跑
      //并依据大小值决定左右方向
      //当遇到空白节点时,cur为目前节点
      if (cur->data > num) {
        cur->left = add_node(num);
      } else{
        cur->right = add_node(num);
      }
    }
  }
  show(root, max, min);
  // 18 22 20 32 18 11 9 0(测资)
}

<<:  【学习笔记】台中捷运票价计算(python)

>>:  CVSS v3.1如何计算其分数(强制性指标)

30天学会Python: Day 9- 程序码也能取名字

自订函式(User Definded Function) 自己定义函式有几个优点: 增加程序码的可读...

【*】AI Go Senior 补充 (2021)

环境安装 在使用Python开发AI时,由於需时时查看处理中的训练资料,於是大多使用Jupyter ...

JavaScript入门 Day10_有关数字的语法2

昨天讲了 Math.abs( ),今天来讲Math.max( ) 那他是什麽呢,来看看下面的 cod...

人工智慧搜寻引擎

想做一个像siri /Hey Google这样的人工智慧搜寻引擎,但是没怎麽碰过,想请教该从哪里开始...

android studio 30天学习笔记 -day 22-Dagger 前言

Dependency Injection Dependency Injection中文翻译为依赖注入...