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

leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-02-18 11:47:49      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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]

先序定根,根据先序的根,中序定左右。然后递归。

 1 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
 2     {
 3         if (preorder.size() == 0)
 4             return NULL;
 5         return buildTreePI(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
 6     }
 7     
 8     TreeNode *buildTreePI(vector<int> &preorder, int preStart, int preEnd, vector<int> &inorder, int inStart, int inEnd)
 9     {
10         TreeNode *root = new TreeNode(preorder[preStart]);
11         int left = 0;
12         if (preStart == preEnd)
13             return root;
14         
15         while (inorder[left + inStart] != preorder[preStart])
16             left++;
17             
18         if (left > 0)
19             root->left = buildTreePI(preorder, preStart + 1, preStart + left, inorder, inStart, inStart + left - 1);
20         if (inStart + left < inEnd)
21             root->right = buildTreePI(preorder, preStart + left + 1, preEnd, inorder, inStart + left + 1, inEnd);
22         return root;
23     }

 

leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4295669.html

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