Title Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
(Non-recursive implementation) the first order traversal of a binary tree.
1 classSolution2 {3 Public:4vector<int> Preordertraversal (TreeNode *root)5 {6vector<int>output;7 if(Root = =NULL)8 {9 returnoutput;Ten } One AStack<treenode*>Nodestack; - Nodestack.push (root); - the while(!nodestack.empty ()) - { -TreeNode *topnode =nodestack.top (); -TreeNode *topleftnode = topnode->left, *toprightnode = topnode->Right ; +Output.push_back (topnode->val); -Nodestack.pop ();//first pop again push. + A if(Toprightnode! = NULL)//because the last access to the right node, the right node is first pressed into the stack. at Nodestack.push (toprightnode); - if(Topleftnode! =NULL) - Nodestack.push (Topleftnode); - } - - returnoutput; in } -};
Leetcode #144 Binary Tree Preorder traversal