144. Binary Tree Preorder Traversal

Posted 蓝色地中海

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了144. Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

LeetCode 144. Binary Tree Preorder Traversal 解题报告