0
点赞
收藏
分享

微信扫一扫

LeetCode-144. Binary Tree Preorder Traversal

SPEIKE 2022-08-10 阅读 36


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;
}
};

 

举报

相关推荐

0 条评论