leetcode105
The binary tree can be reconstructed by the first order and the middle order of the binary tree, or by the first order and the sequential traversal. The value of the root node of the two-fork tree can be found by the ordinal traversal, then the node is divided into the Saozi right subtree by the middle order/post traversal.
In general, there are two methods of iteration and recursion to reconstruct a binary tree. Recursion is time-consuming, and error-prone when determining boundaries, the following code uses iterations, time complexity O (n), and N as the number of tree nodes.
Referring to the iterative idea of the first order traversal, the left node of the left subtree is always pushed into the stack first.
When the top element of the stack is s.top () = = Inorder[0], then the leftmost leaf node of the tree is reached, followed by the iterative thought of the first order traversal and then to the right subtree.
Here a flag flag is set, flag = 1 turns to the right subtree, and the default flag=0 continues the Zuozi left node into the stack.
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten //replacing recursion with an iterative approach One classSolution { A Public: - structtreenode* Reconstructbinarytree (vector<int> pre,vector<int>inch) { - if(pre.size () = =0||inch. Size () = =0) the returnNULL; -Stack<treenode *>s; - inti =0;//index of the pre - intj =0;//in Index + intFlag =0;//flag = 1 turn to right sub-tree -TreeNode *root =NewTreeNode (Pre[i]); +TreeNode *temp =Root; A S.push (temp); ati++;//push One, then i++ - while(I <pre.size ()) { - if(!s.empty () && s.top ()->val = =inch[j]) { -temp =s.top (); - S.pop (); -Flag =1; inJ + +; -}Else{ to if(Flag = =0){ +Temp->left =NewTreeNode (Pre[i]); -temp = temp->Left ; the S.push (temp); *i++; $}Else{Panax NotoginsengFlag =0; -Temp->right =NewTreeNode (Pre[i]); thetemp = temp->Right ; + S.push (temp); Ai++; the } + } - } $ returnRoot; $ } -};
"Binary tree" rebuilding binary tree