Q105. Construct Binary Tree from Preorder and Inorder Traversal
PreviousQ104. Maximum Depth of Binary TreeNextQ106. Construct Binary Tree from Inorder and Postorder Traversal
Last updated
Was this helpful?
Last updated
Was this helpful?
直达:
Given preorder and inorder traversal of a tree, construct the binary tree.
对于先序遍历和中序遍历的两串字符串,先序遍历的第一个字符便是当前树的根节点。为了迭代的使用该算法,需要确定左右两棵子树的先序遍历和中序遍历序列。
对于中序遍历,从当前字符串中找到先序遍历序列的第一个字符,当前字符左侧便为左子树的中序遍历序列(假设有m个字符),右侧便是右子树的中序遍历序列。
对于先序遍历,从第一个元素开始的m个元素是左子树的先序遍历,剩下的便是右子树的先序遍历。
为了节约存储空间,可以构建全局变量的hash表存储树节点在中序遍历序列中的位置。