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]
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution:
很简单,使用栈,先存入右节点,再存入左节点,这样就是先弹出左节点了
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr)return {};
vector<int>res;
stack<TreeNode*>s;
s.push(root);
while (!s.empty())
{
TreeNode* p = s.top();
s.pop();
res.push_back(p->val);
if (p->right)s.push(p->right);
if (p->left)s.push(p->left);
}
return res;
}
};