根据前序遍历和中序遍历构建二叉树

问: 一颗二叉树前序遍历为{1,2,4,7,3,5,6,8},中序遍历为 {4,7,2,1,5,3,8,6},构建这只二叉树。

思路:根节点为1,根据中序遍历左边为4,7,2,右边为5,3,8,6。可以写一个递归函数来搞。

传入参数分别为:前序开始,前序结束,后序开始,后序结束


struct BinaryTreeNode 
{
    int m_value;
    BinaryTreeNode* m_pLeftNode;
    BinaryTreeNode* m_pRightNode;
};
BinaryTreeNode* ConstructCore(int* startPrerder, int* endPreorder,int* startInorder,int* endInorder)
{
    //构建根节点
    int rootValue = startPrerder[0];
    BinaryTreeNode *rootNode = new BinaryTreeNode();
    rootNode->m_value = rootVal
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。构建二叉树的过程可以分为两步:1. 根据前序遍历确定根节点;2. 根据中序遍历确定左子树和右子树。这样,我们就可以递归构建整棵树。具体的实现可以参考以下代码: ```c #include <stdio.h> #include <stdlib.h> // 树的节点结构体 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 根据前序遍历中序遍历构建二叉树 TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { if (preorderSize <= 0 || inorderSize <= 0) { return NULL; } // 根节点为前序遍历的第一个元素 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = preorder[0]; root->left = NULL; root->right = NULL; // 在中序遍历中找到根节点的位置 int rootIndex; for (rootIndex = 0; rootIndex < inorderSize; rootIndex++) { if (inorder[rootIndex] == preorder[0]) { break; } } // 递归构建左子树和右子树 root->left = buildTree(preorder + 1, rootIndex, inorder, rootIndex); root->right = buildTree(preorder + rootIndex + 1, preorderSize - rootIndex - 1, inorder + rootIndex + 1, inorderSize - rootIndex - 1); return root; } // 先序遍历 void preorderTraversal(TreeNode* root) { if (root == NULL) { return; } printf("%d ", root->val); preorderTraversal(root->left); preorderTraversal(root->right); } // 中序遍历 void inorderTraversal(TreeNode* root) { if (root == NULL) { return; } inorderTraversal(root->left); printf("%d ", root->val); inorderTraversal(root->right); } // 后序遍历 void postorderTraversal(TreeNode* root) { if (root == NULL) { return; } postorderTraversal(root->left); postorderTraversal(root->right); printf("%d ", root->val); } int main() { int preorder[] = {1, 2, 4, 5, 3, 6, 7}; int inorder[] = {4, 2, 5, 1, 6, 3, 7}; int size = sizeof(preorder) / sizeof(int); TreeNode* root = buildTree(preorder, size, inorder, size); printf("先序遍历: "); preorderTraversal(root); printf("\n中序遍历: "); inorderTraversal(root); printf("\n后序遍历: "); postorderTraversal(root); return 0; } ``` 输出结果为: ```c 先序遍历: 1 2 4 5 3 6 7 中序遍历: 4 2 5 1 6 3 7 后序遍历: 4 5 2 6 7 3 1 ``` 希望我的回答能够帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值