• [Jobdu] 题目1385:重建二叉树


    根据一棵二叉树的先序遍历和后序遍历,重建二叉树

    例子:

    我们先来看一个例子,二叉树如上图,则先序遍历为:1 2 4 7 3 5 6 8,中序遍历为:4 7 2 1 5 3 8 6

    思路:

    先序遍历中的第一个元素为根节点,这个元素将中序遍历划分为左右两个部分,左边的为左子树的中序遍历,右边的为右子树的中序遍历,同样也可以将先序遍历除了第一个元素以外的划分为两个部分,第一个部分是左子树的先序遍历,第二部分是右子树的先序遍历。

    由此可知,这是一个递归过程,可以利用递归函数来构建二叉树。对于二叉树的这种常见操作要熟悉,实现的代码要会写。

    代码:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 // the binary tree node
     5 typedef struct BTNode{
     6     int key;
     7     struct BTNode *lchild;
     8     struct BTNode *rchild;
     9 }BTNode;
    10 
    11 // find the key in the InOrder array, if not finded then return -1
    12 int findKey(int arr[], int start, int end, int key) {
    13     int i;
    14     for (i = start; i <= end; i++)
    15         if (arr[i] == key)
    16             return i;
    17     return -1;
    18 }
    19 
    20 // create the binary tree by PreOrder and InOrder
    21 BTNode *rebuildTree(int pre[], int startPre, int endPre, int in[], int startIn, int endIn) {
    22     // both order have the same size
    23     if (endPre - startPre != endIn - startIn)
    24         return NULL;
    25     // the root is the first node of PreOrder
    26     BTNode *root = (BTNode *) malloc(sizeof(BTNode));
    27     root->key = pre[startPre];
    28     root->lchild = NULL;
    29     root->rchild = NULL;
    30 
    31     // find the index of root node in the InOrder
    32     int mid = findKey(in, startIn, endIn, pre[startPre]);
    33     if (mid == -1)
    34         return NULL;
    35 
    36     // if the left-subtree exists, create left-subtree
    37     int length;
    38     if (mid > startIn) {
    39         length = mid - startIn;
    40         root->lchild = rebuildTree(pre, startPre + 1, startPre + 1 + length - 1, in, startIn, startIn + length - 1);
    41     }
    42 
    43     // if the right-subtree exists, create right-subtree
    44     if (mid < endIn) {
    45         length = endIn - mid;
    46         root->rchild = rebuildTree(pre, endPre - length + 1, endPre, in, endIn - length + 1, endIn);
    47     }
    48 
    49     return root;
    50 }
    51 
    52 void postTraverse(BTNode *tree) {
    53     if (tree) {
    54         postOrder(tree->lchild);
    55         postOrder(tree->rchild);
    56         printf("%d ", tree->key);
    57     }
    58 }
    59 
    60 int main() {
    61     int preOrder[8] = {1, 2, 4, 7, 3, 5, 6, 8};
    62     int inOrder[8] = {4, 7, 2, 1, 5, 3, 8, 6};
    63     BTNode *root = rebuildTree(preOrder, 0, 7, inOrder, 0, 7);
    64     postTraverse(root);
    65     printf("
    ");
    66     
    67     return 0;
    68 }
  • 相关阅读:
    存储过程访问外部服务器
    MVC4 code first 增加属性,对应自动修改列的方法笔记
    摘抄
    一条命令使win7可以直接运行.net3.5程序
    工作心得
    删除一个不存在的东西可以抛出异常吗
    洛谷P3379 【模板】最近公共祖先(LCA)
    洛谷P1967 货车运输
    洛谷P1653 猴子
    洛谷P2278 [HNOI2003]操作系统
  • 原文地址:https://www.cnblogs.com/tonyhu1993/p/4705800.html
Copyright © 2020-2023  润新知