LeetCode HOT 100 —— 105.从前序与中序遍历序列构造二叉树

题目

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder是同一棵树的中序遍历,请构造二叉树并返回其根节点。

LeetCode HOT 100 —— 105.从前序与中序遍历序列构造二叉树_第1张图片

思路

做这题前可以先看一下代码随想录二叉树——从中序与后序遍历序列构造二叉树,思路一致

前序遍历顺序是:中→左→右
中序遍历顺序是:左→中→右

套用代码随想录二叉树——从中序与后序遍历序列构造二叉树代码可得:

class Solution {
	Map<Integer,Integer> map;//根据数值查位置
	public TreeNode buildTree(int[] preorder,int[] inorder){
		map = new HashMap<>();// 用map保存中序序列的数值对应位置
		int n = inorder.length;
		for(int i= 0; i < n; i++){
			map.put(inorder[i],i);//用map保存中序序列的数值对应的下标位置i
		}
		return findNode(preorder, 0, n, inorder, 0, n);//左闭右开
	}
	
	public TreeNode findNode(int[] preorder,int preBegin,int preEnd,int[] inorder,int inBegin,int inEnd){// 参数里的范围都是前闭后开
		if(preBegin >= preEnd || inBegin >= inEnd){
			return null;
		}
		int rootIndex = map.get(preorder[preBegin]);//找到前序遍历的第一个元素(根节点)在中序遍历中的位置
		TreeNode root = new TreeNode(inorder[rootIndex]);//构造节点,存放根节点值
		int lenOfLeft = rootIndex - inBegin;//得到中序左子树的长度,用来确定切割前序左子树的长度(因为中序左数组长度和前序左子树长度相等)
		root.left = findNode(preorder, preBegin + 1, preBegin + lenOfLeft + 1, 
							inorder, inBegin, rootIndex);//在前序遍历(中左右)中的左数组[preBegin + 1, preBegin + lenOfLeft + 1)(因为preBegin是根节点,要严格的左区间)对应了中序遍历(左中右)中的左数组[inBegin,rootIndex)(因为rootIndex就是根节点,所以左数组到rootIndex - 1为止,注意是开区间)
		root.right = findNode(preorder, preBegin + lenOfLeft + 1, preEnd,
							inorder, rootIndex + 1, inEnd);//在前序遍历(中左右)中的右数组为[preBegin + lenOfLeft + 1,preEnd)对应了中序遍历(左中右)中的右数组[rootIndex + 1,inEnd)(因为rootIndex就是根节点,所以右数组从rootIndex + 1开始)
		return root;
	}
}

你可能感兴趣的:(LeetCode,热题,HOT,100,leetcode,算法,职场和发展)