打印二叉树:
void PrintTree(BinaryTreeNode* pRoot)
{
PrintTreeNode(pRoot);
if(pRoot != NULL)
{
if(pRoot->left != NULL)
PrintTree(pRoot->left);
if(pRoot->right != NULL)
PrintTree(pRoot->right);
}
}
void PrintTreeNode(BinaryTreeNode* pNode)
{
if(pNode != NULL)
{
printf("value of this node is: %d\n", pNode->value);
if(pNode->left != NULL)
printf("value of its left child is: %d.\n", pNode->left->value);
else
printf("left child is null.\n");
if(pNode->right != NULL)
printf("value of its right child is: %d.\n", pNode->right->value);
else
printf("right child is null.\n");
}
else
{
printf("this node is null.\n");
}
printf("\n");
}
销毁二叉树:
void DestroyTree(BinaryTreeNode* root)
{
/*if(pRoot != NULL)
{
BinaryTreeNode* pLeft = pRoot->left;
BinaryTreeNode* pRight = pRoot->right;
delete pRoot;
pRoot = NULL;
DestroyTree(pLeft);
DestroyTree(pRight);
}*/
//应该两个方式都可以,剑指offer里用的上面那种
if(root != NULL)
{
if(root->left!=NULL)
DestroyTree(root->left);
if(root->right!=NULL)
DestroyTree(root->right);
delete root;
root=NULL;
}
}
重建二叉树:
输入:二叉树的前序遍历,中序遍历和结点个数;
输出:根据前序遍历和中序遍历,重建出二叉树,并返回二叉树的根节点
BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder){
int rootValue=startPreorder[0];
BinaryTreeNode* root=new BinaryTreeNode();
root->value=rootValue;
root->left=root->right=NULL;
if(startPreorder==endPreorder){
if(startInorder==endInorder&&*startPreorder==*startInorder)
return root;
else
throw std::exception("Invalid Input");
}
//中序遍历中找出根节点
int* rootInorder=startInorder;
while(*rootInorder!=rootValue&&rootInorder<=endInorder)
++rootInorder;
if(rootInorder>endInorder)
throw std::exception("Invalid Input");
int leftLength = rootInorder - startInorder;
int* leftPreorderEnd = startPreorder + leftLength;
if(leftLength > 0)
{
// 构建左子树
root->left = ConstructCore(startPreorder + 1, leftPreorderEnd,
startInorder, rootInorder - 1);
}
if(leftLength < endPreorder - startPreorder)//这里应该最好不要用if(endInorder>rootInorder)这样的条件判断语句吧?
{
// 构建右子树
root->right = ConstructCore(leftPreorderEnd + 1, endPreorder,
rootInorder + 1, endInorder);
}
return root;
}
BinaryTreeNode* Construct(int* preorder, int* inorder, int length){
if(preorder==NULL||inorder==NULL||length<=0){
throw std::exception("Invalid Input");
}
return ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1);
}