二叉树的先序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
std::stack<TreeNode*> st;
std::vector<int> ans;
TreeNode* p = root;
while(p || !st.empty()){
if(p){
ans.push_back(p->val);
st.push(p);
p = p->left;
}else{
p = st.top(); st.pop();
p = p->right;
}
}
return ans;
}
};
标签:right,TreeNode,val,nullptr,st,二叉树,三序,之非,left
From: https://www.cnblogs.com/gebeng/p/18323271