1. 程式人生 > >JavaScript刷LeetCode -- 106. Construct Binary Tree from Inorder and Postorder Traversal

JavaScript刷LeetCode -- 106. Construct Binary Tree from Inorder and Postorder Traversal

一、題目

  Given inorder and postorder traversal of a tree, construct the binary tree.

  Note:
  You may assume that duplicates do not exist in the tree.

  For example, given

  inorder = [9,3,15,20,7]
  postorder = [9,15,7,20,3]
  Return the following binary tree:

     3
    / \
   9  20
      /  \
     15   7

二、題目大意

  根據二叉樹的中序遍歷和後序遍歷構造一顆二叉樹。

三、解題思路

  這道題需要從這兩個遍歷陣列找出規律:

  9     3     15 20 7
  left  root  right

  9     15 7 20  3
  left  right    root

  後序遍歷陣列的最後一位為根節點,然後通過當前的根節點可以將中序遍歷陣列分成左右兩個子樹的中序遍歷陣列,再根據該下標將後序遍歷陣列也分成左右子樹的後序遍歷陣列,遞迴得出結果。

四、程式碼實現

const buildTree = (inorder, postorder) => {
  if (!inorder) {
    return null
  }

  const val = postorder.pop()
  const root = new TreeNode(val)
  const index = inorder.indexOf(val)
  root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index))
  root.right = buildTree(inorder.slice(index + 1), postorder.slice(index))
  return root
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。