# 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;
}
};

#### LeetCode(144)Binary Tree Preorder Traversal

2014-01-15 06:29:16

#### LeetCode 144 — Binary Tree Preorder Traversal（C++ Java Python）

2014-03-02 22:13:14

#### LeetCode144 Binary Tree Preorder Traversal（迭代实现） Java

2016-04-23 13:14:19

#### 【LeetCode】144 . Binary Tree Preorder Traversal 解题报告

2016-05-22 23:53:41

#### leetcode 144. Binary Tree Preorder Traversal-前序遍历|递归|非递归

2016-05-22 23:24:12

#### leetcode-java-144. Binary Tree Preorder Traversal

2016-06-29 16:46:14

#### 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告

2016-06-01 23:42:08

#### 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal（构造二叉树）】

2015-08-09 06:37:17

#### C++详解Leetcode:105. Construct Binary Tree from Preorder and Inorder Traversal

2017-07-30 17:34:05

#### LeetCode 144 Binary Tree Preorder Traversal（二叉树的前序遍历）+（二叉树、迭代）

2016-03-19 16:15:45