Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:三星网络电视50寸 编辑:程序博客网 时间:2024/04/29 10:00

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

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

解题思路::

解题思路,随便写一个二叉树,然后写出前序和中序遍历的结果会发现特点。

二叉树的首节点必然是前序遍历的第一个节点,以这个节点在中序遍历的结果中作为划分,这个节点左侧的是左子树的节点,右侧是右子树节点。

例如,一个二叉树的前序遍历结果为:6 5 4 8 7 9

中序遍历结果为:4 5 6 7 8 9

前序遍历的第一个节点为6,就是这个二叉树的根节点。以6作为划分,中序遍历6以左的节点就是二叉树的左子树,以右的就是二叉树的右节点。按照此逻辑进行递归操作

构造新树,每次不断的把前序的root找到,用前序构造新树,

学会用容器表示节点,如何判断条件,在中序中选.root.

代码:

template<typename Iter>TreeNode* make(Iter pFirst , Iter pLast , Iter iFirst , Iter iLast) {if(pFirst == pLast) return nullptr;if(iFirst == iLast) return nullptr;int val = *pFirst;auto iRoot = find(iFirst , iLast , val); //找第一个..rootTreeNode* root = new TreeNode(*iRoot);   //赋值了第一个节点int leftSize = iRoot - iFirst; //左移dongroot -> left= make(pFirst+1 , pFirst+leftSize+1 , iFirst , iRoot);root ->right = make(pFirst+leftSize+1 , pLast , iRoot + 1 , iLast);return root;} TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder){  int size = preorder.size();  if (size==0) return nullptr;  return make(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());}


0 0
原创粉丝点击