/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0){
return null;
}
int[] p_index = {postorder.length};
return buildTreeCore(inorder, postorder, 0, (inorder.length - 1), p_index);
}
public TreeNode buildTreeCore(int[] inorder, int[] postorder, int i_l, int i_r, int[] p_index) {
--p_index[0];
if(i_l == i_r){
TreeNode cur_Node = new TreeNode(postorder[p_index[0]]);
return cur_Node;
}else{
int i_temp = 0;
for(int i = i_l; i <= i_r; ++i){
if(inorder[i] == postorder[p_index[0]]){
i_temp = i;
break;
}
}
TreeNode cur_Node = new TreeNode(postorder[p_index[0]]);
if((i_temp + 1) <= i_r){
cur_Node.right = buildTreeCore(inorder, postorder, (i_temp + 1), i_r, p_index);
}
if(i_l <= (i_temp - 1)){
cur_Node.left = buildTreeCore(inorder, postorder, i_l, (i_temp - 1), p_index);
}
return cur_Node;
}
}
}
106. Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2022-01-01 11:35:53 发布