码迷,mamicode.com
首页 > 其他好文 > 详细

construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树

时间:2017-06-18 23:39:22      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:from   order   public   uil   index   UI   tor   div   bsp   

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

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

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
13         if(preorder.size()!=inorder.size()) return NULL;
14         return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
15     }
16     
17     TreeNode *build(vector<int> &preorder, vector<int> &inorder,int s1,int e1,int s2,int e2){
18         if(s1>e1||s2>e2) return NULL;
19         if(s1==e1) return new TreeNode(preorder[s1]);
20         TreeNode *res=new TreeNode(preorder[s1]);
21         int tmp=preorder[s1];
22         int index=0;
23         while((s2+index)<=e2){
24             if(inorder[s2+index]==tmp)
25                 break;
26             index++;
27         }
28         res->left=build(preorder,inorder,s1+1,s1+index,s2,s2+index-1);
29         res->right=build(preorder,inorder,s1+index+1,e1,s2+index+1,e2);
30         return res;
31     }
32 };

 

construct-binary-tree-from-preorder-and-inorder-traversal——前序和中序求二叉树

标签:from   order   public   uil   index   UI   tor   div   bsp   

原文地址:http://www.cnblogs.com/zl1991/p/7045643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!