利用前序遍历和中序遍历构造二叉树


根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3
    / \ 9  20
     / \ 15   7

思想:利用分治的思想来解决该题

具体解题步骤:

  1.根据先序遍历,我们可以知道根节点就是给定数组的第一个元素pre[0],那么我们就可以在中序遍历中找出值等于pre[0]的位置,该位置的前半部分就是左子树,右半部分就是右子树,

  2.重复1,直到遍历完

实现代码如下:

public class Solution { public int preIndex = 0;
//查找pre[pri]的位置 public int find(int[] inorder, int inbegin,int inend,int val){ for(int i = inbegin;i<=inend;i++){ if(inorder[i] == val) return i; } return -1; }
public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin,int inend) { if(inbegin>inend) return null; TreeNode root = new TreeNode(preorder[preIndex]); int index = find(inorder,inbegin,inend,preorder[preIndex]); if(index == -1) return null; preIndex++; root.left = buildTreeChild(preorder,inorder,inbegin,index-1); root.right = buildTreeChild(preorder,inorder,index+1,inend); return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null) return null; return buildTreeChild(preorder,inorder,0,inorder.length-1); } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM