本文主要是介绍LeetCode 106. 从中序与后序遍历序列构造二叉树 java题解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
class Solution {int len;HashMap<Integer,Integer> map;public TreeNode buildTree(int[] inorder, int[] postorder) {len=inorder.length;//两个序列长度是一样的map=new HashMap<>();//保存一个数在中序序列中的indexfor(int i=0;i<len;i++){map.put(inorder[i],i);}return build(inorder,postorder,len-1,0,len-1);}//在后序中的index为根节点,在中序中的left rightpublic TreeNode build(int[] inorder, int[] postorder,int index,int left,int right){if(left>right||index<0){//越界return null;}TreeNode root=new TreeNode(postorder[index]);int root_in=map.get(postorder[index]);//right-root_in-1+1=right-root_in=右子树的长度root.right=build(inorder,postorder,index-1,root_in+1,right);root.left=build(inorder,postorder,index-1-right+root_in,left,root_in-1);return root;}
}
//后序遍历从后往前遍历,确定根节点,根节点在中序中划分左右子树
这篇关于LeetCode 106. 从中序与后序遍历序列构造二叉树 java题解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!