题目
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
思路
参考【数据结构】二叉树(前、中、后)序遍历的递归与非递归算法
实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> temp;
vector<int> res;
if (root == NULL) return res;
temp.push(root);
while (!temp.empty()) {
TreeNode* a = temp.top();
temp.pop();
res.push_back(a->val);
if (a->right != NULL) {
temp.push(a->right);
}
if (a->left != NULL) {
temp.push(a->left);
}
}
return res;
}
};
本文介绍了一种使用迭代算法实现二叉树前序遍历的方法,通过使用栈来代替递归,提供了非递归的解决方案。示例中详细解释了如何遍历一个特定的二叉树并返回其前序遍历结果。
135

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



