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

面试题07. 根据前序和中序重建二叉树

时间:2020-05-09 13:08:27      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:uil   root   重建   treenode   binary   dex   ++   dtree   str   

题目:

技术图片

 

 

解答:

 1 /**
 2  * Definition for a binary tree node.
 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* buildTreeHelper(vector<int> &preorder, int ps, int pe, vector<int> &inorder, int is, int ie)
13     {
14         if ((pe - ps) < 0 || ((pe - ps) != (ie - is)))
15         {
16             return NULL;
17         }
18 
19         TreeNode *root = new TreeNode(preorder[ps]);
20 
21         int index = -1;
22         for (int i = is; i <= ie; i++)
23         {
24             if (inorder[i] == root->val)
25             {
26                 index = i;
27                 break;
28             }
29         }
30 
31         if (-1 == index)
32         {
33             return root;
34         }
35 
36         int leftprelen = index - is;
37         root->left = buildTreeHelper(preorder, ps + 1, ps + leftprelen, inorder, is, index - 1);
38         root->right = buildTreeHelper(preorder, ps + leftprelen + 1, pe, inorder, index + 1, ie);
39         return root;
40     }
41     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
42     {
43         return buildTreeHelper(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() -1);
44     }
45 };

 

面试题07. 根据前序和中序重建二叉树

标签:uil   root   重建   treenode   binary   dex   ++   dtree   str   

原文地址:https://www.cnblogs.com/ocpc/p/12856587.html

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