Construct Binary Tree from Preorder and Inorder
105. Construct Binary Tree from Preorder and Inorder Traversal
Problem Description
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
Intuition
The front element of preorder traversal is the tree’s root node(the middle of inorder traversal). We use it to determine which elements belong the left subtree and the right subtree, and keep comparing the preorder and inorder traversals. This way, we can construct the entire tree from these two traversals.
Algorithm
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 YouChen's Blog!