重建二叉树

打印二叉树:

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值