在本科毕设结束后,我开始刷卡哥的“代码随想录”,每天一节。自己的总结笔记均会放在“算法刷题-代码随想录”该专栏下。
代码随想录此题链接
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
此题可以使用递归遍历(前序),通过后序最后一个元素找到中序的位置,这就是根节点。
然后递归遍历当前根节点的左右孩子。
需要设置一个类变量(对于这个类中所有的函数来说是全局变量)。
HashMap inorderMap = new HashMap();
此题可以使用递归遍历,
三部曲:
HashMap inorderMap = new HashMap();public TreeNode buildTree(int[] inorder, int[] postorder) {for(int i = 0;i < inorder.length;i++){inorderMap.put(inorder[i],i);}TreeNode result = traversal(inorder,0,inorder.length,postorder,0,postorder.length);return result;}public TreeNode traversal(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){//左闭右开if(inEnd <= inBegin || postEnd <= postBegin){return null;}//1.找到后序的最后一个元素作为中序的切割点int rootIndex = inorderMap.get(postorder[postEnd - 1]);//2.TreeNode cur = new TreeNode(inorder[rootIndex]);//左右子树后序切割int lenOfLeft = rootIndex - inBegin;TreeNode leftTreeNode = traversal(inorder,inBegin,rootIndex,postorder,postBegin,postBegin + lenOfLeft);TreeNode rightTreeNode = traversal(inorder,rootIndex + 1,inEnd,postorder,postBegin + lenOfLeft,postEnd - 1);cur.left = leftTreeNode;cur.right = rightTreeNode;return cur;}
暂无
暂无