首页 > 代码库 > LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree. (Medium)
Note:
You may assume that duplicates do not exist in the tree.
分析:
跟前一题方法一样,只需要分析出中序与后序恢复时,需从后序的最后一个元素读出来当做根节点,在中序中寻找其位置。
其余递归过程跟前序中序恢复一致。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 TreeNode* helper(vector<int>& inorder, int inStart, int inEnd, vector<int>& postorder, int postStart, int postEnd) { 13 int sz = inEnd - inStart; 14 if (sz == 0) { 15 return nullptr; 16 } 17 int rootVal = postorder[postEnd - 1]; 18 TreeNode* root = new TreeNode(rootVal); 19 int pos; 20 for (pos = 0; pos < sz; ++pos) { 21 if (inorder[inStart + pos] == rootVal) { 22 break; 23 } 24 } 25 if (pos < 0) { 26 root -> left = nullptr; 27 } 28 else { 29 root -> left = helper(inorder, inStart , inStart + pos, postorder, postStart, postStart + pos); 30 } 31 if (pos + 1 >= sz) { 32 root -> right = nullptr; 33 } 34 else { 35 root -> right = helper(inorder, inStart + pos + 1, inEnd, postorder, postStart + pos, postEnd - 1); 36 } 37 return root; 38 } 39 public: 40 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 41 return helper(inorder, 0, inorder.size(), postorder, 0, postorder.size()); 42 } 43 };
LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。