把题目的要求细化,搞清楚根节点应该作什么,而后剩下的事情抛给前/中/后序的遍历框架,千万不要跳到递归的细节里,相信你的定义java
对于构造二叉树的问题,根节点要作的就是想办法把本身构造出来
咱们确定要遍历数组找到最大值maxVal,把根节点root作出来,而后对maxVal左边的数组和右边的数组进行递归调用,做为root的左右子树。
伪代码数组
TreeNode constructMaxImumBinaryTree(int[] nums){ if(num is empty){ return null; } int maxVal=Integer.MIN_VALUE; int index=0; for(int i=0;i<nums.length;i++){ if(nums[i]>maxVal){ maxVal=nums[i]; index=i; } } TreeNode root=new TreeNode(maxVal); //递归调用构造左右子树 root.left=constructMaximumBinaryTree(nums[0]...index-1); root.right=constructMaximumBinaryTree(nums[index+1...nums.length-1]); return root; }
对于每一个根节点来讲,最重要的是找到当前数组中的最大值以及它的索引,而后前序递归调用构造子树框架
//主函数 TreeNode constructMaximumBinaryTree(int[] nums){ return build(nums,0,nums.length-1); } TreeNode build(int[] nums,int lo,int hi){ //base case if(lo>hi){ return null; } //找到数组中最大值和对应的索引 int index=-1,maxVal=Integer.MIN_VALUE; for(int i=lo;i<=hi;i++){ if(maxVal<nums[i]){ maxVal=nums[i]; index=i; } } TreeNode root=new TreeNode(maxVal); //递归调用构造左右子树 root.left=build(nums,lo,index-1); root.right=build(nums,index+1,hi); return root; }
这个框架用起来简直太爽了,咱们须要考虑的是每一个节点须要干什么
1.须要建立新节点,根据前序遍历的结果来找到根节点的值 root.val=preorder[start];
2.咱们还须要肯定左右子树在数组中的区间,这里须要添加一个新的变量值,leftNum表明的含义是
子树在数组中的长度
leftNum=index-start;
而后进行递归调用构造左右子树函数
public TreeNode buildTree(int[] preorder, int[] inorder) { return buildTree(preorder,0,preorder.length,inorder,0,inorder.length); } public TreeNode buildTree(int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end){ if(pre_start==pre_end){ return null; } //前序遍历 //构造节点 int val =preorder[pre_start]; TreeNode root=new TreeNode(val); int index=-1; for(int i=in_start;i<in_end;i++){ if(root.val==inorder[i]){ index=i; break; } } int leftNum=index-in_start; root.left=buildTree(preorder,pre_start+1,pre_start+leftNum+1,inorder,in_start,index); root.right=buildTree(preorder,pre_start+leftNum+1,pre_end,inorder,index+1,in_end); return root; }