乾貨8 二叉樹

2021-08-04 23:53:45 字數 2452 閱讀 5488

#ifndef __btree_h__

#define __btree_h__

#define bleft 0 // 表示插入二叉樹的左邊

#define bright 1 // 表示插入二叉樹的右邊

#define true 1

#define false 0

typedef char btreedata;

// 二叉樹的結點

typedef struct _btreenode

btreenode;

// 二叉樹

typedef struct _btree

btree;

typedef void (*print_btree)(btreenode*);

// 建立一棵二叉樹

btree *create_btree();

// pos 走的路徑 值類似 110(左右右) 011 (右右左)

// count 代表走的步數

// flag 代表被替換的結點應該插入在新節點的位置,如果是bleft 表示插在左邊,bright表示插在右邊

int btree_insert(btree *tree, btreedata data, int pos, int count, int flag);

void display (btree* tree, print_btree pfunc);

int delete (btree *tree, int pos, int count);

int btree_height (btree *);

int btree_degree (btree *);

int btree_clear (btree *);

int btree_destroy (btree **);

// 前序遍歷

void pre_order (btreenode *node);

void mid_order (btreenode *node);

void last_order (btreenode *node);

#endif // __btree_h__

#include "btree.h"

#include #include btree *create_btree()

int btree_insert(btree *tree, btreedata data, int pos, int count, int flag)

// 把被替換掉的結點插入到新節點下面

if (flag == bleft)

node->lchild = current;

else

node->rchild = current;

// 把新節點插入到二叉樹中,way儲存了應該插入在父節點的左邊還是右邊

if (parent != null)

else

tree->count ++;

return true;

}void r_display(btreenode* node, print_btree pfunc,int gap)

printf ("\n");

return; }

for (i = 0; i < gap; i++)

// 列印結點

// printf ("%c\n", node->data);

pfunc (node);

if (node->lchild != null || node->rchild != null) }

void display (btree* tree, print_btree pfunc)

void r_delete (btree *tree, btreenode* node)

int delete (btree *tree, int pos, int count)

if (parent != null)

else

// 釋放結點

r_delete (tree, current);

return true;

}int r_height (btreenode *node)

int btree_height (btree *tree)

int r_degree (btreenode * node)

return degree;

}int btree_degree (btree *tree)

int btree_clear (btree *tree)

int btree_destroy (btree **tree)

void pre_order (btreenode *node)

void mid_order (btreenode *node)

void last_order (btreenode *node)

8 二叉樹遍歷

typedef struct node node node root 先序遍歷 dlr node root 中序遍歷 ldr node root 後序遍歷 lrd node root 通過先序遍歷和後序遍歷確定不了乙個數。bintree createbtpre return t 分析1 什麼時候訪問...

8 二叉樹複習

構建二叉樹 左子結點小於根節點,右子結點大於根節點 二叉樹 public class binarytree,value 向樹中新增元素key value public void put key key,value value 向指定的樹x中新增key value,並返回新增元素後新的樹 privat...

二叉樹 二叉樹

題目描述 如上所示,由正整數1,2,3 組成了一顆特殊二叉樹。我們已知這個二叉樹的最後乙個結點是n。現在的問題是,結點m所在的子樹中一共包括多少個結點。比如,n 12,m 3那麼上圖中的結點13,14,15以及後面的結點都是不存在的,結點m所在子樹中包括的結點有3,6,7,12,因此結點m的所在子樹...