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

leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-02-18 11:50:07      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

Given inorder and postorder 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> &inorder, vector<int> &postorder) 
 2     {
 3         if (postorder.size() == 0)
 4             return NULL;
 5         TreeNode *root = buildTreePostIn(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
 6         
 7         return root;
 8     }
 9     
10     TreeNode *buildTreePostIn(vector<int> &inorder, int inStart, int inEnd, vector<int> &postorder, int postStart, int postEnd)
11     {
12         int left = 0;
13         TreeNode *root = new TreeNode(postorder[postEnd]);
14         if (postEnd == postStart)
15             return root;
16         
17         while (inorder[inStart + left] != postorder[postEnd])
18             left++;
19         
20         if (left > 0)
21             root->left = buildTreePostIn(inorder, inStart, inStart + left - 1, postorder, postStart, postStart + left - 1);
22         if (inStart + left < inEnd)
23             root->right = buildTreePostIn(inorder, inStart + left + 1, inEnd, postorder, postStart + left, postEnd - 1);
24             
25         return root;
26     }

 

leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

标签:

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

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