1. 程式人生 > 實用技巧 >leetcode-105-從前序與中序遍歷序列構造二叉樹

leetcode-105-從前序與中序遍歷序列構造二叉樹

思路:

preorder 的第一個數就是root

inorder 中root值前後分別是左子樹和右子樹

程式碼:

/**
 * 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:
    unordered_map<int
,int>pos;//建立一個hash儲存位置 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int n=preorder.size(); for(int i=0;i<n;i++) pos[inorder[i]]=i; //遍歷將找到root在inorder 中的位置 return dfs(preorder,inorder,0,n-1,0,n-1);//遞迴處理 } TreeNode* dfs(vector<int
>& preorder,vector<int>&inorder,int pl,int pr,int il,int ir) //pl是前序的起點pr是前序的終點,il是中序的起點,ir是終點 { if(pl>pr) return NULL; int val=preorder[pl];//preorder中的第一個點就是root,val=root int k=pos[val]; //pos[val]就是root在inorder中的位置,inorder中root前為左子樹,後為右子樹。
int len=k-il;//左子樹的長度 auto root=new TreeNode(val); root->left=dfs(preorder,inorder,pl+1,pl+len,il,k-1); root->right=dfs(preorder,inorder,pl+len+1,pr,k+1,ir); return root; } };