重建二叉树
python:
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #前序遍历:根 - 左节点 - 右节点 #中序遍历:左节点- 根 - 右节点 #后序遍历:左节点 - 右节点 - 根节点 class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre or not tin: return None root = TreeNode(pre.pop(0)) index = tin.index(root.val) root.left = self.reConstructBinaryTree(pre,tin[:index]) root.right = self.reConstructBinaryTree(pre,tin[index+1:]) return root
c++
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 if(pre.empty()||vin.empty()) return NULL; 14 //先建立一个头结点 15 TreeNode* head = new TreeNode(pre[0]); 16 //找到vin的根节点的索引 17 //定义一个索引变量 18 int root_index=0; 19 for(int i=0;i<vin.size();i++){ 20 if(vin[i]==pre[0]){ 21 root_index = i; 22 break; 23 } 24 } 25 vector<int> pre_left,pre_right,vin_left,vin_right; 26 for(int i=0;i<root_index;i++){ 27 vin_left.push_back(vin[i]); 28 pre_left.push_back(pre[i+1]); 29 } 30 for(int j=root_index+1;j<pre.size();j++){ 31 pre_right.push_back(pre[j]); 32 vin_right.push_back(vin[j]); 33 } 34 head->left = reConstructBinaryTree(pre_left,vin_left); 35 head->right = reConstructBinaryTree(pre_right,vin_right); 36 return head; 37 } 38 };