Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
可用递归,进行。也可以用迭代。
C++:
1 class Solution { 2 public: 3 void preorder(TreeNode * root, vector<int> &path) 4 { 5 if(root) 6 { 7 path.push_back(root->val); 8 preorder(root->left,path); 9 preorder(root->right,path); 10 } 11 } 12 vector<int> preorderTraversal(TreeNode *root) { 13 vector<int> path; 14 if(root==NULL) return path; 15 preorder(root,path); 16 return path; 17 } 18 };
1 class Solution{ 2 public: 3 vector<int> preorderTraversal(TreeNode *root){ 4 vector<int> path; 5 stack<TreeNode*> stk; 6 while(root!=NULL||!stk.empty()) 7 { 8 if(root!=NULL) 9 { 10 while(root) 11 { 12 path.path_back(root->val); 13 stk.push(root); 14 root=root->left; 15 } 16 }else{ 17 root=stk.top()->right; 18 stk.pop(); 19 } 20 } 21 return path; 22 } 23 };
Python:
1 # Definition for a binary tree node 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 # @param root, a tree node 10 # @return a list of integers 11 def preorderTraversal(self, root): 12 if root==None: 13 return [] 14 if(root): 15 return [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right) 16 17
时间: 2024-10-13 13:07:58