"Leetcode" Binary Tree Preorder traversal

Source: Internet
Author: User

Given a binary tree, return the preorder traversal of its nodes ' values.

For example:

Given binary Tree {1,#,2,3},

1
\
2
/
3
return [+].


Can be recursive, proceed. You can also use iterations.

C++:

1 classSolution {2  Public:3     voidPreorder (TreeNode * root, vector<int> &path)4     {   5         if(Root)6         {7Path.push_back (root->val);8Preorder (root->Left,path);9Preorder (root->Right,path);Ten         } One     } Avector<int> Preordertraversal (TreeNode *root) { -vector<int>path; -         if(Root==null)returnpath; the preorder (root,path); -         returnpath; -     } -};

1 classsolution{2  Public:3vector<int> Preordertraversal (TreeNode *root) {4vector<int>path;5Stack<treenode*>Stk;6          while(root!=null| |!stk.empty ())7         {8             if(root!=NULL)9             {Ten                  while(Root) One                 { APath.path_back (root->val); - Stk.push (root); -Root=root->Left ; the                 } -}Else{ -Root=stk.top ()Right ; - Stk.pop (); +             } -         } +         returnpath; A     } at};

Python:

1 #Definition for a binary tree node2 #class TreeNode:3 #def __init__ (self, x):4 #self.val = x5 #self.left = None6 #self.right = None7 8 classSolution:9     #@param root, a tree nodeTen     #@return A list of integers One     defpreordertraversal (self, root): A         ifroot==None: -             return [] -         if(Root): the             return[Root.val]+self.preordertraversal (Root.left) +self.preordertraversal (root.right) -              -             

"Leetcode" 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.