手撕LeetCode(5)二叉树系列-2 二叉树的建立

二叉树的建立操作

关键思路:搞清楚根节点应该做什么,后续的事情交给前/中/序的遍历框架 。
构造最大二叉树(Leetcode 654题)

方法:构造出根节点。寻找最大值的索引号,索引号左边的是左子树,右边的是右子树,按照这样递规执行操作。 上代码:

TreeNode constructMaximumBinaryTree(int[] nums){
          
   
	return build(nums,0,nums.length-1);
}
TreeNode bulid(int[] nums,int start,int end){
          
   
	if(start> end) return null;
	int index=-1,max=Integer.MIN_VALUE;
	for(int i=start;i<=end;i++){
          
   
		if(nums[i]>max){
          
   
			index=i;
			max=nums[index];
		}
	}
	TreeNode root=new TreeNode(max);
	root.left=build(nums,start,index-1);
	root.right=bulid(nums,index+1,end); 
	return root;
}
前序和中序遍历结果构造二叉树(leetcode 105题)
思路:寻找根节点,可以从前序和中序遍历的特点出发.

对于前序遍历,由于其是根左右,所以首个节点是根节点。 对于中序遍历,由于是左根右,所以根据前序遍历,可以找到根节点,随后可以确定左右节点。 上代码:

TreeNode buildTree(int[] preoder,int[] inorder){
          
   
	return build(preorder,prestart,preend,inorder,instart,inend);
}
TreeNode bulid(int[] preorder,int prestart,int preend,int[] inorder,int instart,int end){
          
   
	if(prestart>preend) return null;
	int root_val=preorder[prestart];
	int index=0;
	for(int i=instart;i<=inend;i++){
          
   
		if(num[i]==root_val){
          
   
			index=i;
			break;
		}
	}
	int leftltngth=index-instart;
	TreeNode root = new TreeNode(root_val);
	root.left=build(preorder,prestart+1,prestart+leftlength,inorder,instart,index-1);
	root.right=bulid(preorder,prestart+leftlength+1,preend,inorder,index+1,inend);
	return root;
}
后续加中序遍历结果构造二叉树(leetcode 106题)

题目:

思路:与上一个思路相同,注意是后续遍历即可。

上代码:

TreeNode buildTree(int[] inoder,int[] postorder){
          
   
	return build(inorder,instart,inend,postorder,poststart,postend);
}
TreeNode bulid(int[] inorder,int instart,int inend,int[] postorder,int poststart,int postend){
          
   
	if(instart>inend) return null;
	int root_val=postorder[postend];
	int index=0;
	for(int i=instart;i<=inend;i++){
          
   
		if(num[i]==root_val){
          
   
			index=i;
			break;
		}
	}
	int leftlength=index-instart;
	TreeNode root = new TreeNode(root_val);
	root.left=build(inorder,instart,index-1,postorder,prestart,prestart+leftlength-1);
	root.right=bulid(inorder,index+1,inend,postorder,poststart+leftlength,postend-1);
	return root;
}
经验分享 程序员 微信小程序 职场和发展