根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3 / 9 20 / 15 7
1 /** 2 * Definition for a binary tree node. 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* dfs(vector<int>& preorder, vector<int>& inorder, int pre, int inl, int inr){ 13 if(inl == inr) return new TreeNode(preorder[pre]); 14 if(inl > inr) return NULL; 15 TreeNode* root = new TreeNode(preorder[pre]); 16 int i = inl; 17 while(preorder[pre] != inorder[i] && i <= inr) i++; 18 root->left = dfs(preorder, inorder, pre+1, inl, i-1); 19 root->right = dfs(preorder, inorder, pre+i-inl+1, i+1, inr); 20 return root; 21 } 22 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { 23 int l = preorder.size()-1; 24 return dfs(preorder, inorder, 0, 0, l); 25 } 26 };
原文地址:https://www.cnblogs.com/mr-stn/p/8977799.html
时间: 2024-09-28 20:02:50