随笔- 509  文章- 0  评论- 151  阅读- 22万 

Construct Binary Tree from Preorder and Inorder Traversal

2014.1.8 00:59

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

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

Solution:

  preorder traversal = root, left, right;

  inorder traversal = left, root, right;

  Thus the first element in the preorder sequence is the root. Find it in the inorder sequence and you know where the left and right subtrees are. Do this procedure recursively and the job is done.

  Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local parameters passed in function calls.

Accepted code:

复制代码
 1 // 1AC, excellent!!!
 2 /**
 3  * Definition for binary tree
 4  * struct TreeNode {
 5  *     int val;
 6  *     TreeNode *left;
 7  *     TreeNode *right;
 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9  * };
10  */
11 class Solution {
12 public:
13     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         return recoverTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
17     }
18 private:
19     TreeNode *recoverTree(vector<int> &preorder, vector<int> &inorder, int l1, int r1, int l2, int r2) {
20         if(l1 > r1){
21             return nullptr;
22         }
23         
24         if(l2 > r2){
25             return nullptr;
26         }
27         
28         TreeNode *root = new TreeNode(preorder[l1]);
29         int i;
30         
31         for(i = l2; i <= r2; ++i){
32             if(inorder[i] == root->val){
33                 break;
34             }
35         }
36         
37         root->left = recoverTree(preorder, inorder, l1 + 1, (l1 + 1)  + (i - 1 - l2), l2, i - 1);
38         root->right = recoverTree(preorder, inorder, r1 - (r2 - i - 1), r1, i + 1, r2);
39         
40         return root;
41     }
42 };
复制代码

 

 posted on   zhuli19901106  阅读(197)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示