题解 | 二叉树先序遍历迭代
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { // 中 左 右 // 入栈:右 左 中 vector<int> result; if (root == nullptr) return result; stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); result.push_back(node->val); if (node->right) s.push(node->right); if (node->left) s.push(node->left); } return result; } };
2023-剑指-二叉树 文章被收录于专栏
2023-剑指-二叉树