106. 從中序與後序遍歷序列構造二叉樹——Java實現

ling08140814發表於2020-12-06

題目描述:

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

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

例如,給出

中序遍歷 inorder = [9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
在這裡插入圖片描述
Java程式碼:

核心程式碼:

	private Map<Integer, Integer> inMap;
	
	public TreeNode myBuildTree(int[] inorder, int[] postorder, int istart, int iend, int pstart, int pend){
        if(pstart > pend)
            return null;

        int post_root =  pend;
        int in_root = inMap.get(postorder[post_root]);
        int num = in_root - istart;

        TreeNode root = new TreeNode(postorder[post_root]);

        root.left = myBuildTree(inorder, postorder, istart, in_root-1, pstart, pstart+num-1);
        root.right = myBuildTree(inorder, postorder, in_root+1, iend, pstart+num, pend-1);
        return root;
    }

    public TreeNode buildTree(int[] inorder, int[] postorder){
        int n = inorder.length;
        inMap = new HashMap<>();
        for(int i=0; i < n; i++){
            inMap.put(inorder[i], i);
        }
        return myBuildTree(inorder, postorder, 0, n-1, 0, n-1);
    }

全部程式碼:

package com.renxia;

import sun.reflect.generics.tree.Tree;

import java.util.HashMap;
import java.util.Map;

public class oneZeroSix {
    private static Map<Integer, Integer> inMap;

    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }

    public  static TreeNode myBuildTree(int[] inorder, int[] postorder, int istart, int iend, int pstart, int pend){
        if(pstart > pend)
            return null;

        int post_root =  pend;
        int in_root = inMap.get(postorder[post_root]);
        int num = in_root - istart;

        TreeNode root = new TreeNode(postorder[post_root]);

        root.left = myBuildTree(inorder, postorder, istart, in_root-1, pstart, pstart+num-1);
        root.right = myBuildTree(inorder, postorder, in_root+1, iend, pstart+num, pend-1);
        return root;
    }

    public static TreeNode buildTree(int[] inorder, int[] postorder){
        int n = inorder.length;
        inMap = new HashMap<>();
        for(int i=0; i < n; i++){
            inMap.put(inorder[i], i);
        }
        return myBuildTree(inorder, postorder, 0, n-1, 0, n-1);
    }

    public static void preOrder(TreeNode root){
        if(root == null)
            return;
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    public static void main(String[] args) {
        int[] inorder = new int[]{9, 3, 15, 20, 7};
        int[] postorder = new int[]{9, 15, 7, 20, 3};
        TreeNode root = buildTree(inorder, postorder);
        preOrder(root);
    }
}

執行結果:

【此處用先序遍歷驗證構造二叉樹的正確性】
在這裡插入圖片描述

相關文章