- 1.题目
- 2.代码
-
题目要求
-
思路:题目要求用先序和中序遍历来建立二叉树。
-
eg:
For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / 9 20 / 15 7
- eg:下面来看一个例子, 某一二叉树的中序和后序遍历分别为:
class Solution { public: TreeNode* buildTree(vector& preorder, vector & inorder) { return SubbuildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1); } TreeNode* SubbuildTree(vector & preorder, int pleft, int pright,vector & inorder, int ileft, int iright) { if ((pleft > pright) || (ileft > iright)) return NULL; int i=0; for (i=ileft;i left=SubbuildTree(preorder,pleft+1,pleft+i-ileft,inorder,ileft,i-1); root ->right=SubbuildTree(preorder,pleft+i-ileft+1,right,inorder,i+1,iright); } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)