105、从前序与中序遍历构造二叉树&&106、从中序与后续遍历构造二叉树

105、从前序与中序遍历构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

//思路:preorder第一个元素为root,在inorder中找到root,root左面为左子树,右面为右子树,不断递归。如下图所示。

/**
 * 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[] preorder,int[] inorder) {
		//思路:在preorder第一个结点是根节点,在inorder中找到root,root左面是左子树,右面是右子树
		if(preorder.length==0)
			return null;
		return buildTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
	}
	public TreeNode buildTree(int[] preorder,int l1,int r1,int[] inorder,int l2,int r2) {
		if(l1>r1)
			return null;
		if(l1==r1)
			return new TreeNode(preorder[l1]);
		TreeNode root=new TreeNode(preorder[l1]);
		int i=l2;
		while(preorder[l1]!=inorder[i])
			i++;
		root.left=buildTree(preorder,l1+1,l1+i-l2,inorder,l2,i-1);
		root.right=buildTree(preorder,l1+i-l2+1,r1,inorder,i+1,r2);
		return root;
	}
}

106、从中序与后续遍历构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 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) {
        //思路:postorder最后一个元素为root,在inorder中找到root,root左面为左子树,右面为右子树,不断递归
		if(postorder.length==0)
			return null;
		return buildTree(postorder,0,postorder.length-1,inorder,0,inorder.length-1);
	}
	public TreeNode buildTree(int[] postorder,int l1,int r1,int[] inorder,int l2,int r2) {
		if(l1>r1)
			return null;
		if(r1==l1)
			return new TreeNode(postorder[l1]);
		TreeNode root=new TreeNode(postorder[r1]);
		int i=l2;
		while(inorder[i]!=postorder[r1])
			i++;
		root.left=buildTree(postorder,l1,l1+i-l2-1,inorder,l2,i-1);
		root.right=buildTree(postorder,l1+i-l2,r1-1,inorder,i+1,r2);
		return root;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值