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.
题意:
给定一个中序和后序遍历序列,构建一个二叉树。
注意:二叉树中元素无重复元素。
思路:
后序遍历中根的顺序是从后往前的,后序遍历最后一个元素是根结点(k),因此遍历后序数组时,应当从后往前搜索,在中序遍历序列中找值为k的下标idx,idx将中序遍历序列分成左右子树,可进行递归操作,后序遍历时先经过右子树的根再经过左子树的根。因此,递归时先递归遍历右子树,再递归遍历左子树。最后把得到的两个子树接到当前的根结点上。
1 | 1 |
1 | class Solution { |