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

【Leetcode】【Medium】Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-05-21 06:40:31      阅读:121      评论: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.

 

解题思路:

给出一个二叉树的中序和后序遍历结果,还原这个二叉树。

对于一个二叉树:

         1
       /        2    3
     / \  /     4  5  6  7

后序遍历结果为:4 5 2 6 7 3 1

中序遍历结果为:4 2 5 1 6 3 7

 

由此可以发现规律:

1、后序遍历的最后一个字符,就是根结点(1)

2、发现根节点后,对应在中序遍历中的位置,则在中序遍历队列中,根节点左边的元素构成根的左子树,根的右边元素构成根的右子树;

3、递归的将左右子树也按照上述规律进行构造,最终还原二叉树。

 

代码:

 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 
11 class Solution {
12 public:
13     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
14         return buildSubtree(postorder, inorder, 0, 
15                             postorder.size()-1, 
16                             0, inorder.size()-1);
17     }
18     
19     TreeNode* buildSubtree(vector<int>& postorder, vector<int>& inorder, 
20                         int p_left, int p_right, int i_left, int i_right) {
21         if (p_left > p_right || i_left > i_right)
22             return NULL;
23         
24         int root = postorder[p_right];
25         TreeNode* node = new TreeNode(postorder[p_right]);
26         
27         int range = 0;
28         for (int j = i_left; j <= i_right; ++j) {
29             if (root == inorder[j]) {
30                 range = j - i_left;
31                 break;
32             }
33         }
34         
35         node->left = buildSubtree(postorder, inorder, 
36                                 p_left, p_left + range - 1, 
37                                 i_left, i_left + range - 1);
38         node->right = buildSubtree(postorder, inorder, 
39                                 p_left + range, p_right - 1, 
40                                 i_left + range + 1, i_right);
41         return node;
42     }
43 };

 

【Leetcode】【Medium】Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/huxiao-tee/p/4518691.html

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