1、来源:144. Binary Tree Preorder Traversal
2、题目:
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?
3、我的代码:/**
* 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> v;
if(root==NULL)
return v;
s.push(root);
while(!s.empty()){
TreeNode*p=s.top();
v.push_back(p->val);
s.pop();
if(p->right!=NULL){
s.push(p->right);
}
if(p->left!=NULL){
s.push(p->left);
}
}
return v;
}
};
4、参考:
1)前序遍历