#include<stack>
struct TreeNode
{
int val = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
};
vector<int> dfs(TreeNode *root) {
vector<int> res;
stack<TreeNode*> _stack;
_stack.push(root);
while (!_stack.empty()) {
TreeNode* treeNode = _stack.top();
_stack.pop();
// 遍历节点
res.push_back(treeNode->val);
// 先压右节点
if (treeNode->right != nullptr) {
_stack.push(treeNode->right);
}
// 再压左节点
if (treeNode->left != nullptr) {
_stack.push(treeNode->left);
}
}
return res;
}
int main()
{
TreeNode root, a, b,c,d;
root.val = 1;
root.left = &a;
root.right = &b;
b.val = 4;
a.val = 2;
a.left = &c;
a.right = &d;
c.val = 5;
d.val = 6;
vector<int> res = dfs(&root);
for (auto x : res) {
cout << x << endl;
}
}
07-16
806
01-21
1万+
03-26