leetcode 43:construct-binary-tree-from-inorder-and-postorder
题目描述
给出一棵树的中序遍历和后序遍历,请构造这颗二叉树
注意:
保证给出的树中不存在重复的节点
题目分析:
这道题是常规题,中序遍历,根节点在最中间,后序遍历的最后一个节点是根节点,根据根节点的值获得在左右中序遍历结果和左右后续遍历的结果,然后重复此过程建立起二叉树。
代码如下:
1 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 2 TreeNode* root = new TreeNode(postorder.back()); 3 vector<int> left_inOrder,right_inOrder,right_postOrder,left_postOrder; 4 int value = postorder.back(); 5 int index = 0; 6 for(int i = 0;i < inorder.size();i++) 7 { 8 if(value == inorder[i]) 9 { 10 index = i; 11 break; 12 } 13 } 14 15 for(int i = 0;i <index;i++) 16 { 17 left_inOrder.push_back(inorder[i]); 18 left_postOrder.push_back(postorder[i]); 19 } 20 21 right_postOrder.push_back(postorder[index]); 22 for(int i = index + 1;i < postorder.size();i++) 23 { 24 right_inOrder.push_back(inorder[i]); 25 right_postOrder.push_back(postorder[i]); 26 } 27 root->left = buildTree(left_inOrder,left_postOrder); 28 root->right = buildTree(right_inOrder, right_postOrder); 29 return root; 30 }