问题描述
给出一棵二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1
\
2
/
3
返回 [1,2,3].
挑战
你能使用非递归实现么?
求解
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
stack<pair<TreeNode *, bool>> s;
s.emplace(root, false);
while (!s.empty()) {
bool visited;
tie(root, visited) = s.top();
s.pop();
if (root == nullptr) {
continue;
}
if (visited) {
res.emplace_back(root->val);
} else {
s.emplace(root->right, false);
s.emplace(root->left, false);
s.emplace(root, true);
}
}
return res;
}
};