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