# Binary Tree Preorder Traversal (leetcode 144）

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?

Show Tags
Show Similar Problems

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == NULL) {
return vector<int>();
}
vector<int> a;
a.push_back(root->val);
vector<int> l = preorderTraversal(root->left);
vector<int> r = preorderTraversal(root->right);
a.insert(a.end(), l.begin(), l.end());
a.insert(a.end(), r.begin(), r.end());
return a;
}
};

// 非递归

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> a;
if (root == NULL) {
return a;
}
stack<TreeNode*> s;
s.push(root);
while(!s.empty()) {
TreeNode* r = s.top();
s.pop();
a.push_back(r->val);
if (r->right != NULL) {
s.push(r->right);
}
if (r->left != NULL) {
s.push(r->left);
}
}
return a;
}
};``````
• 本文已收录于以下专栏：

举报原因： 您举报文章：Binary Tree Preorder Traversal (leetcode 144） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)