Binary Tree Preorder Traversal:使用栈实现
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<const TreeNode *> s;
if (root != nullptr) s.push(root);
while (!s.empty()) {
const TreeNode *p = s.top();
s.pop();
result.push_back(p->val);
if (p->right != nullptr) s.push(p->right);
if (p->left != nullptr) s.push(p->left);
}
return result;
}
};
本文介绍了一种使用栈实现二叉树前序遍历的方法。通过迭代而非递归的方式,该算法有效地完成了节点值的收集。首先将根节点压入栈中,然后不断取出栈顶元素并记录其值,再依次将其右孩子和左孩子压入栈中。
425

被折叠的 条评论
为什么被折叠?



