题目:

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].

Note: Recursive solution is trivial, could you do it iteratively?

说明:

      1)递归和非递归实现,其中非递归有两种方法

      2)复杂度,时间O(n),空间O(n)

实现:

一、递归

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> preorderTraversal(TreeNode *root) {
13       vector<int> root_vec;
14       vector<int> left_vec;
15       vector<int> right_vec;
16       if(root==NULL) return root_vec;
17       root_vec.push_back(root->val);
18       if(root->left!=NULL) left_vec=preorderTraversal(root->left);
19       if(root->right!=NULL) right_vec=preorderTraversal(root->right);
20       root_vec.insert(root_vec.end(),left_vec.begin(),left_vec.end());
21       root_vec.insert(root_vec.end(),right_vec.begin(),right_vec.end());
22       return root_vec;
23     }
24 };
View Code

相关文章: