二叉树

构建二叉树,前序递归遍历及显示

今天看了计算几何-算法应用第二章 线段求交:专题图叠合,在解决一个问题的时候需要用到二叉树,故将这部分知识做一个总结。


图1- 1 树的示例

如图1-1所示为树的概念以及示例图。这种概念类似家谱的概念,一代传一代,子子孙孙有无穷。

二叉树(Binary Tree)是另一种树型结构,他的特点是每个结点至多只有两颗子树。

二叉树的结点由一个数据元素和分别指向其左、右子树的两个分支构成,则表示二叉树的链表中的结点至少包含3个域:数据域和左、右指针域。

今天写了一个简单的程序,构建一个二叉树,并通过前序递归遍历二叉数中的所有数据,并将其显示出来。


图1- 2 二叉树建立

将二叉树中的每个结点的空指针引出一个虚结点,其值为一个特定值,比如”#”,称之为扩展二叉树。扩展二叉树就可以做到一个遍历序列确定一棵二叉树了。如前序遍历序列为ABDG##H###CE#I##F##。

 

图1- 3前序递归遍历

  如图为前序递归遍历 规则是若二叉树为空,则空操作返回,否则先访问根结点,然后前序遍历左子树,再前序遍历右子树。如下图所示,遍历的顺序为ABDGHCEIF。

以下代码实现的功能是建立二叉树,建立二叉树之后对其进行前序递归遍历并显示出来。

举例说明:输入: ABDG##H###CE#I##F##

          输出为:ABDGHCEIF

 


/******************************************* 
 * data   : 2015-04-18         			   *
 * author : shaohui         
 * 功能:二叉树创建,前序递归遍历及显示    *          
 *******************************************/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <ctime>
using namespace std;
typedef char tree_element_type;
typedef struct binary_tree_node {
        tree_element_type data;
        struct binary_tree_node * left_child , * right_child; //左右孩子的指针 
        }binary_tree_node,* binary_tree;
         
int creat_binary_tree ( binary_tree  &t ){
            char c_char;
            scanf("%c",&c_char);
            if(c_char == '#') t = NULL;
            else {
                 t = ( binary_tree_node * )malloc( sizeof( binary_tree_node ) );
                 if( t == NULL ){
                     printf("malloc() error in crete_binary_tree");
                     }
                     t -> data = c_char;
                     creat_binary_tree( t ->left_child );
                     creat_binary_tree( t ->right_child);
                 }
                 return 0;
            }   
void preoder_traverse( binary_tree &t ){
     if( t != NULL )
     {
         printf("%c" , t -> data);
         preoder_traverse( t -> left_child);
         preoder_traverse( t -> right_child);
     } 
     }             
int main()
{
  binary_tree variable_binary_tree;
  creat_binary_tree(variable_binary_tree);
  preoder_traverse( variable_binary_tree );
  system("PAUSE");
  return 0;
  
}

参考引用

(1)http://blog.chinaunix.net/uid-26548237-id-3476141.html

2)严蔚敏老师之《数据结构》



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值