标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
[Solution]
后序定根,中序定左右.
1 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) 2 { 3 if (postorder.size() == 0) 4 return NULL; 5 TreeNode *root = buildTreePostIn(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); 6 7 return root; 8 } 9 10 TreeNode *buildTreePostIn(vector<int> &inorder, int inStart, int inEnd, vector<int> &postorder, int postStart, int postEnd) 11 { 12 int left = 0; 13 TreeNode *root = new TreeNode(postorder[postEnd]); 14 if (postEnd == postStart) 15 return root; 16 17 while (inorder[inStart + left] != postorder[postEnd]) 18 left++; 19 20 if (left > 0) 21 root->left = buildTreePostIn(inorder, inStart, inStart + left - 1, postorder, postStart, postStart + left - 1); 22 if (inStart + left < inEnd) 23 root->right = buildTreePostIn(inorder, inStart + left + 1, inEnd, postorder, postStart + left, postEnd - 1); 24 25 return root; 26 }
leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4295670.html