144. Binary Tree Preorder Traversal
Total Accepted: 110604
Total Submissions: 282561
Difficulty: Medium
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?
递归做太简单了,题目建议用迭代做
/**
* 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) {
stack<TreeNode*> s;
vector<int> vec;
TreeNode *p = root;
if (NULL == p)
return vec;
while (true) {
if (NULL != p) {
vec.push_back(p->val);
s.push(p);
p = p->left;
continue;
}
if (s.empty())
break;
root = s.top()->right;
s.pop();
}
if (NULL != p)
vec.push_back(p->val);
return vec;
}
};