LeetCode 106 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.
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
解:
/*
* @lc app=leetcode id=106 lang=cpp
*
* [106] Construct Binary Tree from Inorder and Postorder 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:
// 后序的最后一个节点为根节点,在中序遍历中找出根节点,根节点前的所有节点为左子树,根节点后的所有节点为右子树。
// is inorder 的起始位置
// ie inorder 的结束位置
// ps postorder 的起始位置
// pe postorder 的结束位置
TreeNode* create(vector<int> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe) {
if(ps > pe){
return nullptr;
}
TreeNode* node = new TreeNode(postorder[pe]);
int iRootS; // inorder 根节点位置
for(int i = is; i <= ie; i++){
if(inorder[i] == node->val){
iRootS = i;
break;
}
}
int leftMarginLen = iRootS - is - 1; // 左位置间距长度,可0,即只有一个节点
int rightMarginLen = ie - iRootS - 1; // 右位置间距长度,可0
node->left = create(inorder, postorder, is, iRootS - 1, ps, ps + leftMarginLen);
int pSubLen = pe - 1; //两个子树总节点长度
node->right = create(inorder, postorder, iRootS + 1, ie, pSubLen - rightMarginLen, pSubLen);
return node;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}
};
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 风屋
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果