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     int Search(vector<int> &vin, int vinLeft, int vinRight, int key) {
    13         int i = (vinLeft + vinRight) >> 1;
    14         int j = i + 1;
    15         while(i >= vinLeft && j <= vinRight) {  // 从中间往两边查找比较快能找到要找的值的位置
    16             if(vin[i] == key) return i;
    17             if(vin[j] == key) return j;
    18             i--;
    19             j++;
    20         }
    21         return vinLeft;
    22     }
    23     TreeNode* myReConstructBinaryTree(vector<int> &pre, int preLeft, int preRight, vector<int> &vin, int vinLeft, int vinRight) {
    24         if(preLeft > preRight || vinLeft > vinRight) return NULL;
    25         TreeNode* t = new TreeNode(pre[preLeft]);
    26         int k = Search(vin, vinLeft, vinRight, pre[preLeft]);   // vin中k位置前的肯定是左子树的各个节点的值,k位置后肯定是右子树的各个节点的值
    27         t->left = myReConstructBinaryTree(pre, preLeft + 1, preLeft + k - vinLeft, vin, vinLeft, k - 1);
    28         t->right = myReConstructBinaryTree(pre, preLeft + k - vinLeft + 1, preRight, vin, k + 1, vinRight);
    29         return t;
    30     }
    31     TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
    32         int Size = pre.size();
    33         return myReConstructBinaryTree(pre, 0, Size - 1, vin, 0, Size - 1);
    34     }
    35 };
  • 相关阅读:
    进程和阻塞
    docker简介
    python===lambda匿名函数===day15
    python----生成器, 生成器函数, 推倒式---13
    python----函数参数---10天
    python---函数 第九天
    python===文件===第八天
    python===基本数据类型 基本增删改查 ===深浅拷贝==第七天
    20180802 (个别内置方法)
    20180730 (面向对象的反射,内置方法)
  • 原文地址:https://www.cnblogs.com/jacen789/p/7737793.html
Copyright © 2011-2022 走看看