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

LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-11-05 17:41:21      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:ret   style   sum   leetcode   efi   rom   nod   help   break   

Given inorder and postorder traversal of a tree, construct the binary tree. (Medium)

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

 

分析:

跟前一题方法一样,只需要分析出中序与后序恢复时,需从后序的最后一个元素读出来当做根节点,在中序中寻找其位置。

其余递归过程跟前序中序恢复一致。

代码:

 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 private:
12     TreeNode* helper(vector<int>& inorder, int inStart, int inEnd, vector<int>& postorder, int postStart, int postEnd) {
13         int sz = inEnd - inStart;
14         if (sz == 0) {
15             return nullptr;
16         }
17         int rootVal = postorder[postEnd - 1];
18         TreeNode* root = new TreeNode(rootVal);
19         int pos;
20         for (pos = 0; pos < sz; ++pos) {
21             if (inorder[inStart + pos] == rootVal) {
22                 break;
23             }
24         }
25         if (pos < 0) {
26             root -> left = nullptr;
27         }
28         else {
29             root -> left = helper(inorder, inStart , inStart + pos, postorder, postStart, postStart + pos);            
30         }
31         if (pos + 1 >= sz) {
32             root -> right = nullptr;
33         }
34         else {
35             root -> right = helper(inorder, inStart + pos + 1, inEnd, postorder, postStart + pos, postEnd - 1);  
36         }
37         return root;
38     }
39 public:
40     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
41         return helper(inorder, 0, inorder.size(), postorder, 0, postorder.size());
42     }
43 };

 

LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal

标签:ret   style   sum   leetcode   efi   rom   nod   help   break   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6033476.html

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