1. 程式人生 > 其它 >Leecode no.889 根據前序和後序遍歷構造二叉樹

Leecode no.889 根據前序和後序遍歷構造二叉樹

package tree;

import java.util.Arrays;

/**
*
* 889. 根據前序和後序遍歷構造二叉樹
* 返回與給定的前序和後序遍歷匹配的任何二叉樹。
*
* pre 和 post 遍歷中的值是不同的正整數。
*
* @author Tang
* @date 2021/7/29
*/
public class ConstructFromPrePost {

/**
* 思路: 對於當前節點 拆分出左子樹有哪些節點,右子樹有哪些節點
* 根據 前序遍歷的第二個節點是左子節點的性質 找到第二個節點在後續遍歷中的位置,從而判斷左子樹節點個數
* @param preorder
* @param postorder
* @return
*/
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
if(preorder.length == 0){
return null;
}
TreeNode root = new TreeNode(preorder[0]);
if(preorder.length == 1){
return root;
}
int leftCount = 0;
for(int i = 0; i < postorder.length; i++){
if(postorder[i] == preorder[1]){
leftCount = i+1;
}
}
//左子樹遞迴
root.left = constructFromPrePost(Arrays.copyOfRange(preorder, 1, leftCount+1),
Arrays.copyOfRange(postorder, 0, leftCount));
//右子樹遞迴
root.right = constructFromPrePost(Arrays.copyOfRange(preorder, leftCount+1, preorder.length),
Arrays.copyOfRange(postorder, leftCount, postorder.length - 1));
return root;
}


public static void main(String[] args) {

}


}