105. プレオーダーおよびインオーダートラバーサルシーケンスからバイナリツリーを構築する
この質問は古典的なデータ構造の質問でもあります. 面接の質問にも遭遇することがあります. preorder と inorder の走査順序がわかれば, preorder 走査から最初の要素がルート ノードであることがわかります, そして inorder 走査の特徴つまり、ルート ノードの左側はすべて左のサブツリーであり、右側はすべて右のサブツリーであり、preorder シーケンスを順番にたどって、inorder シーケンスを分割し、これら 2 つのシーケンスを連続的に組み合わせてコードを記述します。詳細な手順はコードに記載されています。プレオーダーはルート左と右、インオーダーは左ルート右だからです。
アルゴリズムコード
class Solution {
private int preindex; //成员变量 是遍历前序数组的索引 弄成成员变量比较好
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTreeChild(preorder,inorder,0,inorder.length-1);
}
public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inleft,int inright){
if(inleft>inright) return null; //说明当前节点无左右子节点了
TreeNode root = new TreeNode(preorder[preindex]);
int index = find(inorder,preorder[preindex]); //找在中序数组中的索引,用来分组
preindex++;
root.left = buildTreeChild(preorder,inorder,inleft,index-1); //先递归并返回当前节点的左子节点
root.right = buildTreeChild(preorder,inorder,index+1,inright); //后递归并返回当前节点的右子节点
return root; //最后返回当前节点
}
public static int find(int[] inorder,int key){ //用来找每个根节点在后序数组中的下标,并返回下标
int i = 0;
while(inorder[i]!=key){
i++;
}
return i;
}
}
106. インオーダーおよびポストオーダートラバーサルシーケンスからバイナリツリーを構築する
この質問は前の質問とほぼ同じですが、違いは、inorder と postorder が既知であること、postorder はルート ノードである最後の要素によって特徴付けられるため、postorder シーケンスを後ろから前にたどる必要があることです。 。また、左と右のサブツリーを再帰的に返す順序も変わります。残りは前のコードと同じです。なぜなら、順列は左の根と右であり、後順は左と右の根だからです。
アルゴリズムコード
class Solution {
private int postindex;
public TreeNode buildTree(int[] inorder, int[] postorder) {
postindex = postorder.length-1; //指向序列最后一个元素,倒序遍历
return buildTreeChild(postorder,inorder,0,postorder.length-1);
}
private TreeNode buildTreeChild(int[] postorder,int[] inorder ,int inleft,int inright){
if(inleft>inright) return null;
TreeNode root = new TreeNode(postorder[postindex]);
int index = find(inorder,postorder[postindex]);
postindex--;
root.right = buildTreeChild(postorder,inorder,index+1,inright); //这里有区别
root.left = buildTreeChild(postorder,inorder,inleft,index-1); //有区别
return root;
}
private static int find(int[] inorder,int key){
int i = 0;
while(inorder[i] != key){
i++;
}
return i;
}
}