質問
バイナリツリーをトラバースするツリーの配列先行順走査に従って構成されています。
注:
あなたは木の要素を重複していないと仮定することができます。
例えば、与えられました
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
文法の学習
次
next(x) 相当于 next(1)
next(x,n) 相当于以x为数组0元素位置的x(n)
問題の解決策
https://github.com/soulmachine/leetcode
class Solution {
public:
template<typename T>
TreeNode* buildTree(T prefirst,T prelast,T infirst,T inlast){
if(prefirst==prelast) return nullptr;
if(infirst==inlast) return nullptr;
auto root=new TreeNode(*prefirst);
auto inRootPos=find(infirst,inlast,*prefirst);
auto leftSize=distance(infirst,inRootPos);
// 第leftSize个元素并不在左子树中,而包含在右子树中
root->left=buildTree(next(prefirst),next(prefirst,leftSize+1),
infirst,next(infirst,leftSize));
root->right=buildTree(next(prefirst,leftSize+1),prelast,next(inRootPos),inlast);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTree(begin(preorder),end(preorder),begin(inorder),end(inorder));
}
};
playgroudトラック
class Solution {
public:
template<typename T>
TreeNode* buildTree(T prefirst,T prelast,T infirst,T inlast){
cout<<"prefirst : " << *prefirst <<endl;
cout<<"prelast : " << *prelast <<endl;
cout<<"infirst : "<< *infirst <<endl;
cout<<"inlast : " << *inlast <<endl;
if(prefirst==prelast) return nullptr;
if(infirst==inlast) return nullptr;
auto root=new TreeNode(*prefirst);
auto inRootPos=find(infirst,inlast,*prefirst);
auto leftSize=distance(infirst,inRootPos);
cout<<"leftSize : " << leftSize <<endl;
cout<<"-------------------------------------------------"<<endl;
root->left=buildTree(next(prefirst),next(prefirst,leftSize+1),infirst,next(infirst,leftSize));
root->right=buildTree(next(prefirst,leftSize+1),prelast,next(inRootPos),inlast);
return root;
}
輸出
prefirst : 3
prelast : -1094795586
infirst : 9
inlast : -1094795586
leftSize : 1
-------------------------------------------------
prefirst : 9
prelast : 20
infirst : 9
inlast : 3
leftSize : 0
-------------------------------------------------
prefirst : 20
prelast : 20
infirst : 9
inlast : 9
prefirst : 20
prelast : 20
infirst : 3
inlast : 3
prefirst : 20
prelast : -1094795586
infirst : 15
inlast : -1094795586
leftSize : 1
-------------------------------------------------
prefirst : 15
prelast : 7
infirst : 15
inlast : 20
leftSize : 0
-------------------------------------------------
prefirst : 7
prelast : 7
infirst : 15
inlast : 15
prefirst : 7
prelast : 7
infirst : 20
inlast : 20
prefirst : 7
prelast : -1094795586
infirst : 7
inlast : -1094795586
leftSize : 0
-------------------------------------------------
prefirst : -1094795586
prelast : -1094795586
infirst : 7
inlast : 7
prefirst : -1094795586
prelast : -1094795586
infirst : -1094795586
inlast : -1094795586
[3, 9, 20, null, null, 15, 7, null, null, null, null]