- 105&106. Construct Binary Tr
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- 106. Construct Binary Tree from
- Construct Binary Tree from Preor
tag:
- Medium;
question
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
Example:
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
思路:
思路同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(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() -1);
}
TreeNode* buildTree(vector<int>& inorder, int inLeft, int inRight, vector<int>& postorder, int postLeft, int postRight) {
if (inLeft > inRight || postLeft > postRight) return NULL;
int i = 0;
for (i=inLeft; i<=inRight; ++i) {
if (inorder[i] == postorder[postRight]) break;
}
TreeNode *cur = new TreeNode(postorder[postRight]);
cur->left = buildTree(inorder, inLeft, i - 1, postorder, postLeft, postLeft + i - inLeft - 1);
cur->right = buildTree(inorder, i + 1, inRight, postorder, postLeft + i - inLeft, postRight - 1);
return cur;
}
};
网友评论