网站备案查询 美橙,成都小程序制作工作室,网站社区的建设,广州市官方网站根据一棵树的中序遍历与后序遍历构造二叉树。注意:
你可以假设树中没有重复的元素。例如#xff0c;给出中序遍历 inorder [9,3,15,20,7]
后序遍历 postorder [9,15,7,20,3]
返回如下的二叉树#xff1a;3/ \9 20/ \15 7解题思路
根据后序遍历的最后一个元素是父节点给出中序遍历 inorder [9,3,15,20,7]
后序遍历 postorder [9,15,7,20,3]
返回如下的二叉树3/ \9 20/ \15 7
解题思路
根据后序遍历的最后一个元素是父节点在中序遍历中查找父节点父节点的左边为左子树中序遍历的序列右边为右子树中序遍历的序列根据左右子树的长度在后序遍历中找出左右子树的后序遍历的序列再递归下一层。
代码
/*** 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) {return buildT(inorder,0,inorder.length-1,postorder,0,postorder.length-1);}public TreeNode buildT(int[] inorder,int inl,int inr, int[] postorder,int pol,int por) {if(inlinr||polpor) return null; TreeNode treeNodenew TreeNode(postorder[por]);int temp0;while (inorder[inltemp]!postorder[por]) temp;treeNode.leftbuildT(inorder, inl, inltemp-1, postorder, pol, poltemp-1);treeNode.rightbuildT(inorder,inltemp1,inr,postorder,poltemp,por-1);return treeNode;}
}