首页 > 学院 > 开发设计 > 正文

106. Construct Binary Tree from Inorder and Postorder Traversal

2019-11-10 18:46:23
字体:
来源:转载
供稿:网友

跟上一题一样,就注意一下算标记的时候别算错!

/** * 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* create(vector<int>& inorder, vector<int>& postorder, int is, int ie, int ps, int pe){ if(ps > pe) return NULL; if(is > ie) return NULL; TreeNode* node = new TreeNode(postorder[pe]); int pos; for(int i = is; i <= ie; ++ i){ if(node -> val == inorder[i]){ pos = i; break; } } node -> left = create(inorder, postorder, is, pos - 1, ps, ps + pos - is - 1); node -> right = create(inorder, postorder, pos + 1, ie, ps + pos - is, pe - 1); return node; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表