Test instructions: Give a tree the result of its first root traversal.
Ideas:
(1) Deep search method:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Preordertraversal (treenode*root) { - if(!root)returnvector<int>(); -vector<int> Ans (1,root->val); thevector<int> Tmp=preordertraversal (root->Left ); - Ans.insert (Ans.end (), Tmp.begin (), Tmp.end ()); -Tmp=preordertraversal (root->Right ); - Ans.insert (Ans.end (), Tmp.begin (), Tmp.end ()); + returnans; - } + A};
AC Code
(2) is still a deep search method:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int>ans; - voidDFS (treenode*t) - { the if(!t)return; -Ans.push_back (t->val); -DFS (t->Left ); -DFS (t->Right ); + } -vector<int> Preordertraversal (treenode*root) { + DFS (root); A returnans; at } -};
AC Code
(3) Iterative method:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Preordertraversal (treenode*root) { - if(!root)returnvector<int>(); - thestack<pair<treenode*,int>>Stac; -Stac.push (Make_pair (Root,0));//The second parameter is used to record that it has traversed the left/right child -vector<int>ans; - while( !stac.empty ()) + { -treenode* cur=Stac.top (). First; + if(Stac.top (). second==0) Ans.push_back (cur->val); A at if(Cur->left && stac.top (). second==0)//didn't walk through the kids. - { -Cur=cur->Left ; -Stac.top (). second=1; -Stac.push (Make_pair (cur,0)); - } in Else if(Cur->right && stac.top () .second<2)//walk through the left child or have no left child to come in - { toCur=cur->Right ; +Stac.top (). second=2; -Stac.push (Make_pair (cur,0)); the } * ElseStac.pop ();//None of the above two can get in or go through or have no children . $ }Panax Notoginseng returnans; - } the};
AC Code
(4) More iterative method:
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Preordertraversal (treenode*root) { - if(!root)returnvector<int>(); - thevector<int>ans; -Stack<treenode *>Stac; - Stac.push (root); - + while( !stac.empty ()) - { +TreeNode *t=stac.top (); AAns.push_back (t->val); atStac.pop ();//All I need is a child to push the stack, father useless - if(t->right) Stac.push (t->Right ); - if(t->left) Stac.push (t->Left ); - } - returnans; - } in};
AC Code
Leetcode Binary Tree Preorder traversal first root traversal