标签:order break 假设 lib dtree nbsp 节点 get bre
https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ 9 20
/ 15 7
解答
注意中序与后序遍历的特点
后序可以确定当前节点
再从中序遍历中确认左右子树的范围
如此递归 得到所有节点的次序
class Solution {
public:
TreeNode* dfs(vector<int>& inorder, int il, int ir, vector<int>& postorder, int pl, int pr) {
if (ir < il || pr < pl) return NULL;
int rootVal = postorder[pr];
int rooIdx = il;
for ( rooIdx = il; rooIdx <= ir; rooIdx++) {
if (inorder[rooIdx] == rootVal) { break; }
}
int inleft = rooIdx -il;
int inright = ir - rooIdx;
TreeNode* p = new TreeNode(rootVal);
p->left = dfs(inorder, il, il+inleft-1, postorder, pl, pl+ inleft-1);
p->right = dfs(inorder, ir- inright+1, ir, postorder, pr - inright , pr-1);
return p;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return dfs(inorder,0, inorder.size()-1, postorder,0, postorder.size()-1);
}
};
标签:order break 假设 lib dtree nbsp 节点 get bre
原文地址:https://www.cnblogs.com/itdef/p/14824566.html