LeetCode-从中序与后序遍历序列构造二叉树-106--dfs

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

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

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

思路:
分治法,不断将中序数组和后序数组划分为左子树和右子树。
详细题解官网

代码:

class Solution_106 {
	Map<Integer, Integer> map; //存储前序遍历每个节点的下标
	int[] postorder;

	public TreeNode buildTree(int[] inorder, int[] postorder) {
		map = new HashMap<>();
		for (int i = 0; i < inorder.length; i++) {
			map.put(inorder[i], i);
		}
		
		this.postorder = postorder;

		return buildeTree(0,inorder.length - 1, 0, postorder.length - 1);
	}

	/**
	 * 
	 * @param il	当前树所在中序数组的起点
	 * @param ir	当前树所在中序数组的终点
	 * @param pl	当前树所在后序数组的起点
	 * @param pr	当前树所在后序数组的终点
	 * @return
	 */
	private TreeNode buildeTree(int il, int ir, int pl, int pr) {
		if (il > ir || pl > pr) {
			return null;
		}
		
		TreeNode root = new TreeNode(postorder[pr]);
		int mid = map.get(postorder[pr]);
		
		root.left = buildeTree(il, mid - 1,pl, pl + mid - il - 1);
		root.right = buildeTree(mid + 1, ir, pl + mid - il, pr -1);
		
		return root;
	}
}

发布了84 篇原创文章 · 获赞 50 · 访问量 7051

猜你喜欢

转载自blog.csdn.net/qq_43115606/article/details/103438129
今日推荐