码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Binary Tree Preorder Traversal

时间:2015-04-08 23:04:50      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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             

 

【leetcode】Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4404368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!