[LeetCode] [Study Notes] 105. Construct a binary tree from preorder and inorder traversal sequences

105. Construct Binary Tree from Preorder and Inorder Traversal Sequences

Given two integer arrays preorderand inorder, where is the preorder traversalpreorder of a binary tree and is the inorder traversal of the same tree , construct a binary tree and return its root node.inorder

Example 1:

输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]

Example 2:

输入: preorder = [-1], inorder = [-1]
输出: [-1]

hint:

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorderand inorderhave no repeating elements
  • inorderBoth appear inpreorder
  • preorder Guaranteed to be the preorder traversal sequence of the binary tree
  • inorder Guaranteed to be the inorder traversal sequence of a binary tree

problem solving ideas

recursion

  1. Find the root node (that is, preorderthe first number of the array)
  2. According to the root node, distinguish the left and right subtrees (that is, find inorderthe subscript of the array corresponding to the root node val)
    • Left subtree child node: all the numbers beforeinorder the corresponding subscript .
    • Right subtree child node: all numbers afterinorder the corresponding subscript .
  3. Collect the array of child nodes and traverse each to form a binary tree.

Code

var buildTree = function(preorder, inorder) {
    
    
  if(preorder.length===0) return null;

  let rootNode=preorder[0];
  let leftLength=inorder.indexOf(rootNode);
  let root=new TreeNode(rootNode);

  root.left=buildTree(preorder.slice(1,leftLength+1),inorder.slice(0,leftLength));
  root.right=buildTree(preorder.slice(leftLength+1),inorder.slice(leftLength+1));

  return root;
};

Guess you like

Origin blog.csdn.net/weixin_45944495/article/details/128323670