Topic: Construct a binary tree through the central and post-order traversal sequences of Binary Trees
Similarly, it is completely feasible to use the divide and conquer method, but the code for running this method in LeetCode always reports an error:
Memory Limit Exceeded.
StackTo build a binary tree.
The method is similar to the method of constructing a binary tree by means of first-order and last-order traversal, but we still need to make some changes:
IfFrom the back to the frontWhen processing the sequence in the middle and back order, the processing is as follows:
Reverse_PZ success? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> latency + aGq1/PX08r3PC9wPgo8cD48L3A + CjxpbWcgc3JjPQ =" "alt =" \ ">
In this way, the processing method is similar to the first-middle-order method. It only adds the left child to the right child, and vice versa. The implementation code is as follows:
TreeNode * buildTree_in_post (vector
& Inorder, vector
& Postorder) {stack
S; int len = (int) inorder. size (); if (len = 0) return NULL; int in_ptr, post_ptr; // It is used to process in_ptr = post_ptr = len-1 for the middle and back orders respectively; // process TreeNode * root = new TreeNode (postorder [post_ptr]) from the last element of the sequence; // construct the root node, the last element of the Post-order traversal is the root node value TreeNode * pCur = root; // It is used to save the current processing node of the tree int flag = 0; // It is used to determine whether to construct the left node post_ptr --; s. push (root); while (post_ptr>-1) // process to pOstorder [0] {if (! S. empty () & s. top ()-> val = inorder [in_ptr]) {pCur = s. top (); s. pop (); in_ptr --; flag = 1;} else {if (flag = 1) // construct the left node {pCur-> left = new TreeNode (postorder [post_ptr]); pCur = pCur-> left; s. push (pCur); post_ptr --; flag = 0;} else // construct the right node {pCur-> right = new TreeNode (postorder [post_ptr]); pCur = pCur-> right; s. push (pCur); post_ptr -- ;}} return root ;}