您的位置:首页 > 职场人生

[面试真题] LeetCode:Construct Binary Tree from Inorder and Postorder Traversal

2013-05-12 13:54 579 查看
Given inorder and postorder traversal of a tree, construct the binary tree.

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

解法:递归求解,思路同上一篇博客中用先序和中序构造二叉树类似。

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode *buildTree(vector<int> &postorder,int ph, int pe, vector<int> &inorder, int ih, int ie){
TreeNode *root;
if(pe - ph < 0){
return NULL;
}
root = new TreeNode(postorder[pe]);
int index = ih-1;
while(++index <= ie && inorder[index] != postorder[pe]){
}
int leftPostLen = index - ih;
root->left = buildTree(postorder, ph, ph+leftPostLen-1, inorder, ih, index-1);
root->right = buildTree(postorder, ph+leftPostLen, pe-1, inorder, index+1, ie);
return root;
}

public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return buildTree(postorder, 0, postorder.size()-1, inorder, 0, inorder.size()-1);
}
};


Run Status: Accepted!
Program Runtime: 152 milli secs

Progress: 202/202 test cases passed.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐