Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
题解:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> q;
if (root == NULL) {
return {};
}
q.push(root);
vector<int> res;
while (q.empty() == false) {
TreeNode *t = q.top();
q.pop();
res.push_back(t->val);
if (t->right != NULL) {
q.push(t->right);
}
if (t->left != NULL) {
q.push(t->left);
}
}
return res;
}
};