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

    //输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
    //例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。


    1
    作者:技术不宅 2 链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6 3 来源:牛客网 4 5 #include <iostream> 6 #include <vector> 7 using namespace std; 8 9 10 struct TreeNode { 11  int val; 12  TreeNode *left; 13  TreeNode *right; 14  TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 }; 16 17 struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<intin) 18 { 19  if (pre.size() == NULL) 20   return NULL; 21  TreeNode* root = new TreeNode(pre[0]); 22  int i; 23  for (i = 0; i < in.size() && in[i] != pre[0]; i++); 24  vector<int> pre_left, in_left,pre_right,in_right; 25  int pre_i = 1; 26  for (int j = 0; j < in.size(); j++) 27  { 28   if (j < i) 29   { 30    in_left.push_back(in[j]); 31    pre_left.push_back(pre[pre_i]); 32    pre_i++; 33   } 34   else if (j>i) 35   { 36    in_right.push_back(in[j]); 37    pre_right.push_back(pre[pre_i]); 38    pre_i++; 39   } 40  } 41  root->left = reConstructBinaryTree(pre_left, in_left); 42  root->right = reConstructBinaryTree(pre_right, in_right); 43  return root; 44 } 45 46 int main() 47 { 48  vector<int> pre = { 12473568 }; 49  vector<intin = { 47215386 }; 50  TreeNode* root= reConstructBinaryTree(pre, in); 51  int a = 0; 52 }
  • 相关阅读:
    334 Increasing Triplet Subsequence 递增的三元子序列
    332 Reconstruct Itinerary 重建行程单
    331 Verify Preorder Serialization of a Binary Tree 验证二叉树的前序序列化
    330 Patching Array
    329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径
    328 Odd Even Linked List 奇偶链表
    327 Count of Range Sum 区间和计数
    326 Power of Three 3的幂
    Java中的Class.forName
    巧用Java中Calendar工具类
  • 原文地址:https://www.cnblogs.com/dangeal/p/7834436.html
Copyright © 2011-2022 走看看