void insert(int val, int parent, int flg); 将值为val的元素插入到二叉树中。此节点的父节点编号为parent,如果parent项为0,表示插入元素为根结点。如果flg为-1,则此节点为父节点的左子,如果flg为1,则此节点为父节点的右子。 二叉树的节点编号按照插入顺序逐一递增,编号从1开始。 例如:
voidBinTree::p_order(BinNode* Tree, int* &pointer, int &index)const{ if (Tree) { pointer[index++] = Tree->data; p_order(Tree->lChild, pointer, index); p_order(Tree->rChild, pointer, index); } }
在递归的基础上:
1 2 3 4 5 6
int* BinTree::p_traversal()const{ int* p = newint[count]; int i = 0; p_order(root, p, i); return p; }
0x04 m_traversal
中序遍历的递归函数表示(注意此处要引用传递):
1 2 3 4 5 6 7
voidBinTree::m_order(BinNode* Tree, int* &pointer, int &index)const{ if (Tree) { m_order(Tree->lChild, pointer, index); pointer[index++] = Tree->data; m_order(Tree->rChild, pointer, index); } }
在递归的基础上:
1 2 3 4 5 6
int* BinTree::m_traversal()const{ int* p = newint[count]; int i = 0; m_order(root, p, i); return p; }
0x05 countNode
返回结点个数。
1 2 3
intBinTree::countNode()const{ return count; }
0x06 height
递归遍历求二叉树高度。
1 2 3 4 5 6 7 8 9
intBinTree::getHeight(BinNode* Tree)const{ if (Tree == NULL) return0; else { int m = getHeight(Tree->lChild); int n = getHeight(Tree->rChild); return (m > n) ? m + 1 : n + 1; } }
voidBinTree::destroyTree(BinNode* Tree){ while (Tree) { BinNode* left = Tree->lChild; BinNode* right = Tree->rChild; delete Tree; Tree = NULL; if (left) destroyTree(left); if (right) destroyTree(right); } }