使用C++实现根据树的前序和中序遍历重构树结构

本文介绍了如何使用C++实现从给定的前序和中序遍历序列重建一棵二叉树。首先定义二叉树节点结构,然后通过递归方式,利用前序遍历中的第一个元素作为根节点,找到中序遍历中根节点的位置,从而划分左右子树,分别构建子树,最终完成树的重构。测试代码展示了整个过程并打印了重建后的树结构。
摘要由CSDN通过智能技术生成

树的遍历方式被分为前序、中序、后序,其中采用前序+中序或者后序+中序的组合可以构建每一的一棵树。本文采用C++,根据用户提供的前序和中序构建树结构。

首先,定义树的结点:

struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

树的重构代码如下:

BinaryTreeNode* rebuild_tree_form_aheadAndMiddle(int* ahead,int* middle,int length)
{
    if(ahead==nullptr||middle==nullptr||length<=0)
    {
        return nullptr;
    }
    //如何从前序和中序中抽取根节点,并据此拆分左右子树
    int root_value=ahead[0];
    BinaryTreeNode *tree_node=new BinaryTreeNode();
    tree_node->m_nValue=root_value;
    tree_node->m_pLeft=tree_node->m_pRight=nullptr;
    if(length==1)
    {
        return tree_node;
    }
    int root_index;
    for(root_index=0;root_index<length;root_index++)
    {
        if(middle[root_index]==root_value)
        {
            break;
        }
    }
    
    // cout<<"length="<<length<<",the node is:"<<tree_node->m_nValue<<",root_index="<<root_index<<endl;
    tree_node->m_pLeft=rebuild_tree_form_aheadAndMiddle(&(ahead[1]),middle,root_index);
    tree_node->m_pRight=rebuild_tree_form_aheadAndMiddle(&(ahead[root_index+1]),&(middle[root_index+1]),length-root_index-1);
    return tree_node;
}

代码中,首先对输入信息的正确性进行判断,目的是使代码更加健壮。

前序遍历的数列中,根节点总是第一个出现,因此根节点的值为前序遍历中下标为0的数值。在中序遍历中查找根节点数值所在的下标root_index。root_index将中序遍历分为了两个部分,在其左边的数组均出现在根节点的左子树中,右边的数组均出现在其右子树中。

递归的将左右子树重构,即可获取最终的树结构。

为了验证程序能正常使用,可以使用以下测试代码进行测试:

void PrintTree(const BinaryTreeNode* pRoot)
{
    PrintTreeNode(pRoot);

    if(pRoot != nullptr)
    {
        if(pRoot->m_pLeft != nullptr)
            PrintTree(pRoot->m_pLeft);

        if(pRoot->m_pRight != nullptr)
            PrintTree(pRoot->m_pRight);
    }
}
void PrintTreeNode(const BinaryTreeNode* pNode)
{
    if(pNode != nullptr)
    {
        printf("value of this node is: %d\n", pNode->m_nValue);

        if(pNode->m_pLeft != nullptr)
            printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
        else
            printf("left child is nullptr.\n");

        if(pNode->m_pRight != nullptr)
            printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
        else
            printf("right child is nullptr.\n");
    }
    else
    {
        printf("this node is nullptr.\n");
    }

    printf("\n");
}
void DestroyTree(BinaryTreeNode* pRoot)
{
    if(pRoot != nullptr)
    {
        BinaryTreeNode* pLeft = pRoot->m_pLeft;
        BinaryTreeNode* pRight = pRoot->m_pRight;

        delete pRoot;
        pRoot = nullptr;

        DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}
void test7()
{
    int ahead_array[] = {1, 2, 4, 7, 3, 5, 6, 8};
    int middle_array[] = {4, 7, 2, 1, 5, 3, 8, 6};
    int length = 8;
    printf("The preorder sequence is: ");
    for (int i = 0; i < length; ++i)
        printf("%d ", ahead_array[i]);
    printf("\n");

    printf("The inorder sequence is: ");
    for (int i = 0; i < length; ++i)
        printf("%d ", middle_array[i]);
    printf("\n");
    BinaryTreeNode *root = rebuild_tree_form_aheadAndMiddle(ahead_array, middle_array, length);
    PrintTree(root);
    DestroyTree(root);
}
int main(int argc, char *argv[])
{
    test7();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个经典的二叉重构问题,可以通过递归的方式求解。具体实现过程如下: 1. 以preOrder的第一个结点作为当前根节点,从inOrder中找到该节点的位置m,将inOrder序列分成左右两半,左半部分为左子的inOrder序列,右半部分为右子的inOrder序列。 2. 根据左子inOrder序列的长度,可以得到左子的preOrder序列和右子的preOrder序列,递归构造左右子。 3. 重构二叉后,按照后序遍历的顺序输出节点序列。 下面是C++实现代码: ```c++ #include<iostream> #include<vector> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode* buildTree(vector<int>& preOrder, vector<int>& inOrder) { if (preOrder.empty() || inOrder.empty()) return NULL; int rootVal = preOrder[0]; TreeNode* root = new TreeNode(rootVal); int pos = find(inOrder.begin(), inOrder.end(), rootVal) - inOrder.begin(); vector<int> leftInOrder(inOrder.begin(), inOrder.begin() + pos); vector<int> rightInOrder(inOrder.begin() + pos + 1, inOrder.end()); vector<int> leftPreOrder(preOrder.begin() + 1, preOrder.begin() + pos + 1); vector<int> rightPreOrder(preOrder.begin() + pos + 1, preOrder.end()); root->left = buildTree(leftPreOrder, leftInOrder); root->right = buildTree(rightPreOrder, rightInOrder); return root; } vector<int> postOrder(TreeNode* root) { vector<int> res; if (!root) return res; vector<int> left = postOrder(root->left); vector<int> right = postOrder(root->right); res.insert(res.end(), left.begin(), left.end()); res.insert(res.end(), right.begin(), right.end()); res.push_back(root->val); return res; } int main() { vector<int> preOrder = { 'A','B','D','G','H','C','E','I','F' }; vector<int> inOrder = { 'G','D','H','B','A','E','I','C','F' }; TreeNode* root = buildTree(preOrder, inOrder); vector<int> post = postOrder(root); for (int i = 0; i < post.size(); i++) { cout << post[i] << " "; } return 0; } ``` 输出结果为:G H D B I E F C A。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值