题目:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
/**
* 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 preorderTraversal(TreeNode* root) {
/*
*给定一个二叉树,返回它的 前序 遍历。
*/
vector res;
stack st;
if(root == nullptr) return res;
st.push(root);
while(!st.empty()) {
TreeNode *cur = st.top();
st.pop();
res.push_back(cur->val);
if(cur->right != nullptr) st.push(cur->right);
if(cur->left != nullptr) st.push(cur->left);
}
return res;
}
};