/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int post_id;
int []inorder;
int []postorder;
HashMap<Integer,Integer> map = new HashMap<>();
public TreeNode helper(int left,int right)
{
//如果没有二叉树结点可以构造,就结束
if(left > right)
{
return null;
}
//后序遍历序列中最后一个结点是根节点
int root_val = postorder[post_id];
TreeNode root = new TreeNode(root_val);
//从中序序列中获得根节点的位置
int index = map.get(root_val);
//此时后序序列中倒数第二个为根结点
post_id--;
//构建右子树
root.right = helper(index+1,right);
//构建左子树
root.left = helper(left,index-1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.inorder = inorder;
this.postorder = postorder;
post_id = postorder.length - 1;
int idx = 0 ;
for(Integer val : inorder)
{
map.put(val,idx++);
}
return helper(0,inorder.length - 1);
}
}
8.根据中序和后序遍历序列构建二叉树(最为经典的递归解法)
最新推荐文章于 2022-06-23 01:04:33 发布