当前位置: 首页 > 后端技术 > Java

LeetCode-106-Constructabinarytreefromthein-orderandpost-ordertraversalsequences

时间:2023-04-01 21:05:54 Java

Constructabinarytreefromthein-orderandpost-ordertraversalsequences题目描述:Constructabinarytreebasedonthein-order树的遍历和后序遍历。注意:您可以假设树中没有重复元素。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:递归根据中序遍历和后序遍历的性质,用递归的方式解决。递归过程如下:首先,如果中序遍历序列或后序遍历序列为空,则直接返回一棵空树;因为后序遍历序列的最后一个值是根节点,所以先根据这个初始化获取当前根节点root;然后根据根节点root在中序遍历序列中的位置,根节点前面的值为当前根节点的左子树节点,得到当前根的左右子树节点个数节点;然后调用递归方法得到当前根节点的左右子树;最后将根返回为恢复的树。importcom.kaesar.leetcode.TreeNode;importjava.util.Arrays;publicclassLeetCode_106{publicstaticTreeNodebuildTree(int[]inorder,int[]postorder){//如果中序遍历序列或后序遍历序列为空,直接返回空树if(inorder==null||inorder.length==0){returnnull;}//后序遍历序列的最后一个值为根节点的值introotVal=postorder[postorder.length-1];TreeNoderoot=newTreeNode(rootVal);int左计数=0;//inorder遍历序列前的值为左子树的节点,得到左子树的节点个数for(intval:inorder){if(val!=rootVal){leftCount++;}else{休息;}}//递归获取当前根节点的左右子树root.left=buildTree(Arrays.copyOfRange(inorder,0,leftCount),Arrays.copyOfRange(postorder,0,leftCount));root.right=buildTree(Arrays.copyOfRange(inorder,leftCount+1,inorder.length),Arrays.copyOfRange(postorder,leftCount,inorder.length-1));返回根;}民众cstaticvoidmain(String[]args){//测试用例//Inorder遍历序列int[]inorder=newint[]{9,3,15,20,7};//后序遍历序列int[]postorder=newint[]{9,15,7,20,3};buildTree(中序,后序).print();}}【每日留言】命运负责洗牌,而出牌的是我们!

最新推荐
猜你喜欢