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

144. Binary Tree Preorder Traversal

时间:2017-02-11 10:52:36      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:int   node   binary   ret   state   one   ini   span   and   

Problem Statement

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?

solution one:

traverse: 

 1 /**
 2  * Definition for a binary tree node.
 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     void preorderTraverse(TreeNode *node, vector<int>& preorder){
13         if(node == NULL){
14             return;
15         }
16         
17         preorder.push_back(node->val);
18         preorderTraverse(node->left, preorder);
19         preorderTraverse(node->right, preorder);
20         return;
21     }
22     
23     vector<int> preorderTraversal(TreeNode* root) {
24         vector<int> preorder;
25         preorderTraverse(root, preorder);
26         return preorder;       
27     }
28 };

Divide and conquer:

 1 /**
 2  * Definition for a binary tree node.
 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     // this version is divide && conquer
13     vector<int> preorderTraversal(TreeNode* root) {
14         vector<int> preorder;
15         if(root == NULL){
16             return preorder;
17         }
18         // divide
19         vector<int> left = preorderTraversal(root->left);
20         vector<int> right = preorderTraversal(root->right);
21         // conquer
22         preorder.push_back(root->val);
23         preorder.insert(preorder.end(), left.begin(), left.end());
24         preorder.insert(preorder.end(), right.begin(), right.end());
25         return preorder;
26     }
27 };

 

144. Binary Tree Preorder Traversal

标签:int   node   binary   ret   state   one   ini   span   and   

原文地址:http://www.cnblogs.com/wdw828/p/6388579.html

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