题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/** * 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) { if(!pre.size()) return nullptr; int root_ele = pre[0], root_idx_in_vin = 0; // 构建递归的子任务是寻找每个子树的根节点 for(int i = 0; i < vin.size(); i++){ if(vin[i] == root_ele){ root_idx_in_vin = i; break; } } vector<int> pre_left, pre_right, vin_left, vin_right; for(int i = 0; i < root_idx_in_vin; i++){ pre_left.push_back(pre[i+1]); // 从非root结点开始 vin_left.push_back(vin[i]); } for(int i = root_idx_in_vin+1; i < pre.size(); i++){ pre_right.push_back(pre[i]); vin_right.push_back(vin[i]); } TreeNode* root = new TreeNode(0); root->val = root_ele; root->left = reConstructBinaryTree(pre_left, vin_left); root->right = reConstructBinaryTree(pre_right, vin_right); return root; } };