给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: map<int,int> index; TreeNode* myBuildTree(vector<int>& preorder, vector<int>& inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right){ if(preorder_right-preorder_left<0) return nullptr;//先序序列已遍历完毕 //构造当前节点 TreeNode* node = new TreeNode(preorder[preorder_left]); //确定当前节点在中序序列中的位置 int inorder_node = index[node->val]; //确定当前节点的左子树的节点数 int leftsize = inorder_node - inorder_left; //递归构造该节点的左右子树 node->left= myBuildTree(preorder,inorder,preorder_left+1,preorder_left+leftsize,inorder_left,inorder_node-1); node->right= myBuildTree(preorder,inorder,preorder_left+leftsize+1,preorder_right,inorder_node+1,inorder_right); return node; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int n = preorder.size(); //对inoder序列构造从值到索引的映射,以便能根据值快速找到在inorder中的索引 for(int i=0;i<n;i++){ index[inorder[i]] =i; } //构造二叉树 return myBuildTree(preorder,inorder,0,n-1,0,n-1); } };
标签:preorder,遍历,TreeNode,int,中序,right,二叉树,inorder,left From: https://www.cnblogs.com/yueshengd/p/18629954