leetcode 105, https://leetcode.com/problems...node
Given preorder and inorder traversal of a tree, construct the binary tree.ui
Note:
You may assume that duplicates do not exist in the tree.code
For example, given遞歸
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:leetcode
3
/ \
9 20get
/ \
15 7it
前序遍歷的第一個節點就是root,用這個root能夠把中序遍歷的列表正好分爲兩段,分別是左右子樹。左右子樹的size,正好是前序有序的兩段。
所以,能夠根據前序第一個節點,劃分出兩個前序+中序的序列,遞歸生成子樹。再將子樹鏈接到root上。io
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int size = preorder.size(); if (size == 0) { return NULL; } int p_idx = 0; int root_val = preorder[p_idx++]; TreeNode* root = new TreeNode(root_val); vector<int> p1,p2; vector<int> i1,i2; bool in_left = true; for (int i = 0; i < size; i++) { if (inorder[i] == root_val) { in_left = false; continue; } if (in_left) { i1.push_back(inorder[i]); p1.push_back(preorder[p_idx++]); } else { i2.push_back(inorder[i]); p2.push_back(preorder[p_idx++]); } } root->left = buildTree(p1, i1); root->right = buildTree(p2, i2); return root; } };