Traversing the binary tree structure 889. The preamble and subsequent (non-recursive)

Topic connection:

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/

Subject to the effect:

Chinese title

AC Code:

 1 TreeNode * construcuFormPrePost(vrctor<int>& pre, vector<int>&post){
 2 
 3     if(pre.empty())
 4         return NULL;
 5     stack<TreeNode*>S;
 6     auto root = new Treenode(pre[0]);
 7     S.push(root);
 8     for(int i = 1, j = 0; i <pre.size(); i++){
 9         auto node = new TreeNode(pre[i]);
10         while(S.top()->val == post[j])S.pop(), j++;
11         if(!S.top()->left)
12             S.top()->left = node;
13         else 
14             S.top()->right = node;
15         S.push(node);     
16     }
17     return root;
18 }

 

Guess you like

Origin www.cnblogs.com/letlifestop/p/11517160.html