實現二叉樹的基本操作:建立、遍歷、計算深度、結點數、葉子數等。
輸入c,先序建立二叉樹,#表示空節點;
輸入h:計算二叉樹的高度;
輸入l:計算二叉樹的葉子個數;
輸入n:計算二叉樹節點總個數;
輸入1:先序遍歷二叉樹;
輸入2:中序遍歷二叉樹;
輸入3:後續遍歷二叉樹;
輸入f:查詢值=x的節點的個數;
輸入p:以縮格文字形式輸出所有節點。
例如:輸入
c
abc##de#g##f###hl
n123
fap
result:
created success!
height=5.
leaf=3.
nodes=7.
preorder is:a b c d e g f .
inorder is:c b e g d f a .
postorder is:c g e f d b a .
the count of a is 1.
the tree is:
a bcd
eg
f
#include using namespace std;
typedef char datatype ;
class binarytree;
class bintreenode
bintreenode(datatype x, bintreenode *left = null, bintreenode *right = null) : data(x), leftchild(left),
rightchild(right) {};
~bintreenode() {};
};class binarytree ;
binarytree(datatype val)
~binarytree()
void creatbintree() ;
int isempty()
bintreenode *parent(bintreenode *current)
bintreenode *leftchild(bintreenode *current)
bintreenode *rightchild(bintreenode *current)
int height()
int size()
bintreenode *getroot() const
void preorder()
void inorder()
void postorder()
void levelorder()
int leaf()
int countnumber(char &ch)
void print()
};void binarytree::print(bintreenode *subtree,int dep)
cout << subtree->data << endl;
print(subtree->leftchild, dep + 1);
print(subtree->rightchild, dep + 1);
}bintreenode *binarytree::parent(bintreenode *subtree, bintreenode *current)
bintreenode *p;
if ((p = parent(subtree->leftchild, current)) != null) return p;
else return parent(subtree->rightchild, current);
}void binarytree::destroy(bintreenode * subtree)
}int binarytree::leaf(bintreenode * subtree)const
int binarytree::countnumber(bintreenode *subtree, char &ch)
int binarytree::height(bintreenode *subtree)const
int binarytree::size(bintreenode *subtree)const
void binarytree::inorder(bintreenode *subtree)
}void binarytree::preorder(bintreenode *subtree)
}void binarytree::postorder(bintreenode *subtree)
}int treenum;
void binarytree::creatbintree(bintreenode *&subtree) else
}void run()
}}int main()
二叉樹基本操作
tree.h ifndef tree h define tree h include typedef int element 定義二叉樹 typedef struct nodetreenode void preorder treenode root 遞迴前序遍歷 void inorder treen...
二叉樹基本操作
一.二叉樹的定義 二.二叉樹的建立 定義一棵無資料的二叉樹 6 int left size 7 int right size 為了操作簡便,我們定義一棵不需要儲存資料的二叉樹,只要能儲存節點之間的邏輯關係就行,所以用兩個陣列來表示。left i 第i個節點的左子節點的序號 right i 第i個節點...
二叉樹基本操作
include include define maxsize 100 typedef char elemtype typedef struct node btnode void createbtnode btnode b,char str 由str串建立二叉鏈 j ch str j btnode f...