zoukankan      html  css  js  c++  java
  • 剑指offer 重建二叉树

    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
     
    思路:由于前序遍历的第一个数总是树的根节点的值,扫描中序遍历的序列,我们可以知道根节点的值在中序遍历序列的位置,进而我们知道树的左子树的中序遍历序列即为根节点的值的左边序列,并且知道左子树的序列的长度, 树的右子树的中序遍历序列即为根节点的值的右边序列。由此左右子树的长度,我们可以从树的前序遍历序列中得到左右子树的前序遍历。接下来以递归的方式再处理左右子树。
     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
    13         int length = pre.size();
    14         if (length == 0) {
    15             return nullptr;
    16         }
    17         return Construct(pre, vin, 0, length - 1, 0, length - 1);
    18     }
    19 private:
    20     TreeNode* Construct(vector<int> pre, vector<int> vin, int pre_l, int pre_r, 
    21                         int vin_l, int vin_r) {
    22         int rootValue = pre[pre_l]; //记录根节点的值
    23         TreeNode *root = new TreeNode(rootValue); //创建根节点
    24         //如果只有一个值
    25         if (pre_l == pre_r) {
    26             if (vin_l == vin_r && pre[pre_l] == vin[vin_l])
    27                 return root;
    28             else
    29                 return nullptr;
    30         } 
    31         int i = vin_l; //记录根节点的值在中序遍历序列的位置
    32         while (i <= vin_r && vin[i] != rootValue) {
    33             i++;
    34         }
    35         int leftlength = i - vin_l; //左子树长度
    36         //左子树长度大于零
    37         if (leftlength > 0) {
    38             root->left = Construct(pre, vin, pre_l + 1, pre_l + leftlength, 
    39                                    vin_l, i - 1);
    40         }
    41         //左子树长度小于传入序列长度-1(除去根节点),说明右子树长度大于零
    42         if (leftlength < (pre_r - pre_l)) {
    43             root->right = Construct(pre, vin, pre_l + leftlength + 1, pre_r, 
    44                                     i + 1, vin_r);
    45         }
    46         return root;
    47     }
    48 };
  • 相关阅读:
    不可重叠最长重复子串
    离散化
    hash是一门优雅的暴力
    Detect the Virus (字符串转化+AC自动机)
    病毒侵袭(AC自动机变形)
    hdu2069(Coin Change)
    Hie with the Pie(poj3311)
    poj3254(状压dp入门第一道题,很详细)
    map系统学习
    ACM-ICPC 2018 南京赛区网络预赛 B. The writing on the wall
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11213653.html
Copyright © 2011-2022 走看看