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 };