從前序與中序遍歷序列構造二叉樹&&從中序與後序遍歷序列構造二叉樹

注:題目源自leetcode105&106,題目說明中元素是不重複的,所以採取map保存元素與索引的映射,便於尋找元素,如果需要構造有重複元素的樹,請自行尋找相應元素的索引(無非就是遍歷,所以我懶得寫了,下面的內容呢,整理於這裏)

從前序與中序遍歷序列構造二叉樹

題目

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。注意:
你可以假設樹中沒有重複的元素。
例如,給出前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:

	3
   / \
 9    20
     /  \
    15   7

解析

  • 前序遍歷(根結點…左結點…右結點)
  • 中序遍歷(左結點…根結點…右結點)
  • 後序遍歷(左結點…右結點…根結點)
  1. 題目說明沒有重複結點,可以使用一個HashMap存儲中序遍歷中結點值與索引。
  2. 根據節點索引的關係,不斷遞歸,構造結點。

在這裏插入圖片描述

代碼

function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}


/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

var buildTree = function(preorder, inorder) {
    //因爲題目明確說明沒有重複元素,所以可以利用map保存索引
    let map = new Map();
    inorder.forEach((ele,index)=>map.set(ele,index));

    function build(preStart,preEnd,inStart,inEnd) {
        if(preStart > preEnd || inStart > inEnd) return null;

        let root = new TreeNode(preorder[preStart]);

        //根節點在inorder中的索引
        let preIndex = map.get(preorder[preStart]);

        // 根據左結點在 preorder 和 inorder 中的位置 求出左結點
        root.left = build(preStart + 1, preStart + preIndex - inStart, inStart, preIndex -1);

        // 根據右結點在 preorder 和 inorder 中的位置 求出右結點
        root.right = build(preStart + preIndex - inStart + 1, preEnd,preIndex + 1, inEnd);

        return root;
    }

    return build(0,preorder.length - 1,0,inorder.length - 1);
};

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

題目

根據一棵樹的中序遍歷與後序遍歷構造二叉樹。注意:
你可以假設樹中沒有重複的元素。
例如,給出中序遍歷 inorder = [9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

解析

同上

代碼

function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}


/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

var buildTree = function(inorder, postorder) {
    let map = new Map();

    //保存元素與索引的映射
    inorder.forEach((ele,index)=>map.set(ele,index));

    function build(postStart,postEnd,inStart,inEnd) {
        if(postStart > postEnd || inStart > inEnd) return null;

        let root = new TreeNode(postorder[postEnd]);

        let pIndex = map.get(postorder[postEnd]);

        root.left = build(postStart, pIndex - inStart - 1 + postStart, inStart, pIndex- 1);
        root.right = build(pIndex - inStart + postStart, postEnd - 1, pIndex + 1, inEnd);

        return root;
    }

    return build(0,postorder.length - 1,0,inorder.length - 1);
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章