Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

LeetCode: Construct Binary Tree from Inorder and Postorder Traversal

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

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

地址:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

算法:根据中序和后序构造出二叉树。细心一点应该不会错。代码:

 1 /**
 2  * Definition for binary tree
 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 public:
12     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
13         if(inorder.empty()) return NULL;
14         return subBuildTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
15     }
16     TreeNode *subBuildTree(vector<int> &inorder, vector<int> &postorder, int inbegin, int inend, int postbegin, int postend){
17         TreeNode *root = new TreeNode(postorder[postend]);
18         if(inbegin == inend && postbegin == postend){
19             return root;
20         }
21         int key = postorder[postend];
22         int i = inbegin;
23         while(i <= inend && inorder[i] != key)  ++i;
24         if(i > inbegin){
25             root->left = subBuildTree(inorder,postorder,inbegin,i-1,postbegin,postbegin+i-1-inbegin);
26         }
27         if(inend > i){
28             root->right = subBuildTree(inorder,postorder,i+1,inend,postbegin+i-inbegin,postend-1);
29         }
30         return root;
31     }
32 };

 

posted on 2014-08-27 21:31  Boostable  阅读(166)  评论(0编辑  收藏  举报