LeetCode OJ: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.
同样是给出了不会有重复数字的条件,用递归较容易实现,代码如下:
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 public: 12 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 13 if(inorder.size() == 0) 14 return NULL; 15 return createTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); 16 } 17 18 TreeNode* createTree(vector<int> & inorder, int inBegin, int inEnd, 19 vector<int> & postorder, int postBegin, int postEnd) 20 { 21 if(inBegin > inEnd) return NULL; 22 int rootVal = postorder[postEnd]; 23 int mid; 24 for(int i = inBegin; i <= inEnd; ++i){ 25 if(inorder[i] == rootVal){ 26 mid = i; 27 break; 28 } 29 } 30 int len = mid - inBegin; 31 TreeNode * left = createTree(inorder, inBegin, mid - 1, //边界条件同样应该注意 32 postorder, postBegin, postBegin + len - 1); 33 TreeNode * right = createTree(inorder, mid + 1, inEnd, 34 postorder, postBegin + len, postEnd - 1); 35 TreeNode * root = new TreeNode(rootVal); 36 root->left = left; 37 root->right = right; 38 return root; 39 } 40 };
java版本的代码如下所示,没有区别:
1 public class Solution { 2 public TreeNode buildTree(int[] inorder, int[] postorder) { 3 if(inorder.length == 0) 4 return null; 5 return createTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); 6 } 7 8 public TreeNode createTree(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd){ 9 if(inEnd < inBegin) 10 return null; 11 int rootVal = postorder[postEnd]; 12 int mid = 0; 13 for(int i = inBegin; i <= inEnd; ++i){ 14 if(inorder[i] == rootVal){ 15 mid = i; 16 break; 17 } 18 } 19 int len = mid - inBegin; 20 TreeNode leftNode = createTree(inorder, inBegin, mid - 1, postorder, postBegin, postBegin + len - 1); 21 TreeNode rightNode = createTree(inorder, mid + 1, inEnd, postorder, postBegin + len, postEnd - 1); 22 TreeNode root = new TreeNode(rootVal); 23 root.left = leftNode; 24 root.right = rightNode; 25 return root; 26 } 27 }