106.Construct Binary Tree from Inorder and Postorder Traversal

題目描述(中等難度)

在這裏插入圖片描述

思路分析

可以先看一下 105 題,直接在 105 題的基礎上改了,大家也可以先根據 105 題改一改。

105 題給的是先序遍歷和中序遍歷,這裏把先序遍歷換成了後序遍歷。

區別在於先序遍歷的順序是 根節點 -> 左子樹 -> 右子樹。

後序遍歷的順序是 左子樹 -> 右子樹 -> 根節點。

我們當然還是先確定根節點,然後在中序遍歷中找根節點的位置,然後分出左子樹和右子樹。

對於之前的解法一,傳數組的兩個邊界,影響不大,只要重新計算邊界就可以了。

解法一

常規解法,利用遞歸,傳遞左子樹和右子樹的數組範圍即可。

import java.util.HashMap;

class TreeNode{
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x){val=x;}
}

public class Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal {
	
	public static TreeNode buildTree(int[]inorder,int[]postorder) {
		HashMap<Integer,Integer>map=new HashMap<>();
		for(int i=0;i<inorder.length;i++) {
			map.put(inorder[i],i);
		}
		return builderTreeHelper(inorder,0,inorder.length,postorder,0,postorder.length,map);
	}

	private static TreeNode builderTreeHelper(int[] inorder, int i_start, int i_end, int[] postorder, int p_start, int p_end,HashMap<Integer,Integer>map) {
		
		if(p_start==p_end) return null;
		int root_val=postorder[p_end-1];
		TreeNode root=new TreeNode(root_val);
		int i_root_index=map.get(root_val);
		int leftNum=i_root_index-i_start;
		root.left = builderTreeHelper(inorder, i_start, i_root_index, postorder, p_start, p_start + leftNum, map);
	    root.right = builderTreeHelper(inorder, i_root_index + 1, i_end, postorder, p_start + leftNum, p_end - 1,map);
		return root;
	}
	public static void main(String args[]) {
		int[] preorder= {9,3,15,20,7};
		int[] inorder= {9,15,7,20,3};
		
		TreeNode ans=buildTree(preorder,inorder);
		System.out.println(ans.val);
	}
}

在這裏插入圖片描述

參考文獻

1.https://zhuanlan.zhihu.com/p/74277078

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章