/**
* Definition for binary tree
* 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> result;
if(root == NULL){
return result;
}
TreeNode *p = root;
std::stack<TreeNode *> mystack;
while(p || !mystack.empty()){
if(p) {
result.push_back(p->val);
mystack.push(p);
p = p->left;
} else {
p = mystack.top();
p = p->right;
mystack.pop();
}
}
return result;
}
};
版权声明:本文博主原创文章,博客,未经同意不得转载。