题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int vinSize = vin.size(); if(vinSize == 0) return NULL; vector<int>pre_left,pre_right,vin_left,vin_right; int val = pre[0]; int i; for(i = 0; i < vinSize; i ++) { if(vin[i] == val){ break; } } int index = i; TreeNode* tree = new TreeNode(val); for(i = 0; i < vinSize; i++ ) { if(i < index) { vin_left.push_back(vin[i]); pre_left.push_back(pre[i+1]); } else if(i > index) { vin_right.push_back(vin[i]); pre_right.push_back(pre[i]); } } tree->left = reConstructBinaryTree(pre_left,vin_left); tree->right = reConstructBinaryTree(pre_right,vin_right); return tree; } };
原文地址:https://www.cnblogs.com/grglym/p/8908069.html
时间: 2024-11-10 07:53:12