首页 > 代码库 > 144. Binary Tree Preorder Traversal

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 && conquer13     vector<int> preorderTraversal(TreeNode* root) {14         vector<int> preorder;15         if(root == NULL){16             return preorder;17         }18         // divide19         vector<int> left = preorderTraversal(root->left);20         vector<int> right = preorderTraversal(root->right);21         // conquer22         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