1. 程式人生 > 其它 >LeetCode0106-從中序與後序遍歷序列構造二叉樹

LeetCode0106-從中序與後序遍歷序列構造二叉樹

技術標籤:LeetCode二叉樹演算法leetcode資料結構從中序與後序遍歷序列構造二叉樹

LeetCode0106-從中序與後序遍歷序列構造二叉樹

題目:

根據一棵樹的中序遍歷與後序遍歷構造二叉樹。

注意:
你可以假設樹中沒有重複的元素。

例如,給出

中序遍歷 inorder = [9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]

返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

程式碼:

/**
 * 0106-從中序與後序遍歷序列構造二叉樹
 * 根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
 * <p>
 * 注意:
 * 你可以假設樹中沒有重複的元素。
 * <p>
 * 例如,給出
 * <p>
 * 中序遍歷 inorder = [9,3,15,20,7]
 * 後序遍歷 postorder = [9,15,7,20,3]
 * <p>
 * 返回如下的二叉樹:
 * <p>
 * 3
 * / \
 * 9  20
 * /  \
 * 15   7
 */
import java.util.HashMap; import java.util.Map; /** * Definition for a binary tree node */ class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode() { } public TreeNode(int val) { this.val = val; } public TreeNode(int val, TreeNode left,
TreeNode right) { this.val = val; this.left = left; this.right = right; } } /** * 遞迴 */ class Solution { int postIndex; int[] postorder; int[] inorder; Map<Integer, Integer> indexMap = new HashMap<>(); public TreeNode buildTree(int[] inorder,
int[] postorder) { this.inorder = inorder; this.postorder = postorder; // 從後序遍歷的最後一個元素開始 postIndex = postorder.length - 1; // 建立(元素,下標)鍵值對的雜湊表 int index = 0; for (Integer val : inorder) { indexMap.put(val, index++); } return helper(0, inorder.length - 1); } private TreeNode helper(int leftIndex, int rightIndex) { // 如果沒有節點構造二叉樹就結束 if (leftIndex > rightIndex) { return null; } // 選擇postIndex 位置元素作為當前子樹根節點 int rootVal = postorder[postIndex]; TreeNode root = new TreeNode(rootVal); // 根據root所在位置分為左右倆顆子樹 int index = indexMap.get(rootVal); // 下標減一 postIndex--; /** * 這裡需要注意的點: * 需要先建立右子樹,再建立左子樹的依賴關係 * 在後序遍歷的陣列中整個陣列是先儲存左子樹的節點再儲存右子樹的節點,最後儲存 * 根節點,如果按每次選擇[後序遍歷的最後一個節點]為根節點,則先被構造出來的應該是 * 右子樹 */ // 構造右子樹 root.right = helper(index + 1, rightIndex); // 構造左子樹 root.left = helper(leftIndex, index - 1); return root; } } /** * 測試 */ public class Study0106 { public static void main(String[] args) { preOrder(new Solution().buildTree(new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3})); } private static void preOrder(TreeNode root) { if (root == null) { return; } System.out.print(root.val + "\t"); preOrder(root.left); preOrder(root.right); } }

結果:

在這裡插入圖片描述