2019年9月13日
LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
C++, LeetCode, 算法, 编程
0 Comments
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
解析:
根据中序和后序遍历顺序生成二叉树。题目类似于LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(postorder, 0, postorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* buildTree(vector<int>& postorder, int pLeft, int pRight, vector<int>& inorder, int iLeft, int iRight)
{
if(pLeft > pRight || iLeft > iRight) return NULL;
int i =0;
for(i = iLeft; i <= iRight; ++i)
{
if(postorder[pRight] == inorder[i])
break;
}
TreeNode *cur = new TreeNode(postorder[pRight]);
cur->left = buildTree(postorder, pLeft, pLeft+i-iLeft-1, inorder, iLeft, i-1);
cur->right = buildTree(postorder, pLeft+i-iLeft, pRight-1, inorder, i+1, iRight);
return cur;
}
};