LeetCode(七)105. Construct Binary Tree from Preorder and Inorder Traversal

问题描述:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

解题思路:
特点:
先序遍历的第一个节点为树根节点
中序遍历中依据先序遍历的根节点可以将整棵树分割为左子树和右子树两个部分

1、通过先序遍历找到第一个点作为根节点,在中序遍历中找到根节点并记录rootIndex。
2、记录左子树的长度并在先序遍历中依据这个长度找到左子树的区间,用同样方法可以找到右子树的区间。
3、递归的建立左子树和右子树

代码

class Solution {
	/*找到根节点,划分为左右子树序列,继续的递归调用,直到所有的节点构造完成
	 * 1 [2 4 5] [3 6 7]    [4 2 5] 1 [6 3 7]
	 */
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
	
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int preLength = preorder.length;
        int inLength = inorder.length;
        return buildTree(preorder, 0, preLength-1, inorder, 0, inLength-1);
    }
    
    public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
    	if(preStart > preEnd||inStart > inEnd) {
    		return null;
    	}
    	int rootVal = preorder[preStart];
    	int rootIndex = 0;
    	//在中序遍历序列中找到根节点的值
    	for(int i = inStart; i <= inEnd; i++) {
    		if(rootVal == inorder[i]) {
    			rootIndex = i;
    			break;
    		}
    	}
    	TreeNode root = new TreeNode(rootVal);
    	//找到左子树的长度
    	int len = rootIndex - inStart;
    	//将先序序列和中序序列分别分割为左子树的部分,继续调用 
    	root.left = buildTree(preorder, preStart+1, preStart+len, inorder, inStart, rootIndex-1);
    	//将先序序列和中序序列分别分割为右子树的部分,继续调用
    	root.right = buildTree(preorder, preStart+len+1, preEnd, inorder, rootIndex+1, inEnd);
    	return root;
    }
}

Reference:https://www.cnblogs.com/springfor/p/3884034.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值