Leetcode #144 Binary Tree Preorder traversal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.