iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 7

Day7-Construct Binary Tree from Inorder and Postorder Traversal

  • 分享至 

  • xImage
  •  

今天的題目為106.Construct Binary Tree from Inorder and Postorder Traversal,題目再叫我們以中序和後序的結果,重建原本的二元樹結構。

以下為程式碼與解說:

import java.util.*;

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

class Solution {
    private Map<Integer, Integer> inorderIndexMap; // 儲存中序遍歷中每個值的位置
    private int postIndex; // 指向目前處理的後序節點索引

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        inorderIndexMap = new HashMap<>();
        postIndex = postorder.length - 1; // 從後序最後一個元素開始(根節點)

        // 建立中序索引對照表,方便快速查找根節點位置
        for (int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }

        // 從整個範圍開始建樹
        return buildSubTree(postorder, 0, inorder.length - 1);
    }

    private TreeNode buildSubTree(int[] postorder, int inLeft, int inRight) {
        // 如果左邊界超過右邊界,表示這部分沒有節點
        if (inLeft > inRight) return null;

        // 取得目前的根節點值(來自後序遍歷)
        int rootVal = postorder[postIndex--];
        TreeNode root = new TreeNode(rootVal);

        // 在中序遍歷中找到根節點的位置
        int inorderIndex = inorderIndexMap.get(rootVal);

        // 注意:先建右子樹,再建左子樹(因為 postorder 是從右到左)
        root.right = buildSubTree(postorder, inorderIndex + 1, inRight);
        root.left = buildSubTree(postorder, inLeft, inorderIndex - 1);

        return root;
    }
}

今天的跟昨天的很像,但前序變後序,有點相似但還是不一樣


上一篇
Day6-Construct Binary Tree from Preorder and Inorder Traversal
下一篇
Day8-Binary Tree Level Order Traversal II
系列文
Leetcode30天挑戰15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言