JavaScript:leetcode_105. 從前序與中序遍歷序列構造二叉樹(前序找根,中序分左右,遞歸)

題目說明

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

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

例如,給出

前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]
返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

解題思路一

  1. 前序找根中序分左右遞歸即可。
  2. 根爲前序第一個值。let root = new TreeNode(preorder[0]);
  3. 找到根在中序中的位置let rootIndex = inorder.indexOf(root.val);
  4. 左右分開。left爲左中序,right爲右中序,preLeft爲左前序,preRight爲右
 		let left = inorder.slice(0, rootIndex);
    	let right = inorder.slice(rootIndex + 1, inorder.length);
   	 	let preLeft = preorder.slice(1, left.length + 1);
    	let preRight = preorder.slice(left.length + 1);
  1. 找到左右各自的前中序列。即可遞歸找根了。

代碼實現一

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

var buildTree = function buildTree(preorder, inorder) {
    if (preorder.length == 0) {
        return null;
    }
    let root = new TreeNode(preorder[0]);
    if (preorder.length == 1) {
        return root;
    }
    let rootIndex = inorder.indexOf(root.val);
    let left = inorder.slice(0, rootIndex);
    let right = inorder.slice(rootIndex + 1, inorder.length);
    let preLeft = preorder.slice(1, left.length + 1);
    let preRight = preorder.slice(left.length + 1);
    left.length && (root.left = buildTree(preLeft, left));
    right.length && (root.right = buildTree(preRight, right));
    return root;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章