# Binary Tree Preorder Traversal (leetcode 144）

539人阅读 评论(0)

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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：36432次
• 积分：886
• 等级：
• 排名：千里之外
• 原创：50篇
• 转载：15篇
• 译文：1篇
• 评论：3条
评论排行
最新评论