二叉树的pre-order,post-order,in-order遍历用recursion实现非常简单,本文中的代码为基于stack的非recursion的实现方法。另外还有level-order的实现。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
Pre-order
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
if(root==NULL) return vector<int> ();
vector<int> result;
stack<TreeNode *> tmp;
tmp.push(root);
while(!tmp.empty()){
TreeNode *cur = tmp.top();
result.push_back(cur->val);
tmp.pop();
if(cur->right!=NULL) tmp.push(cur->right);
if(cur->left!=NULL) tmp.push(cur->left);
}
return result;
}
};
Post-order
class Solution {
public:
&nb

本文介绍了二叉树的前序、后序、中序和层序遍历的非递归实现,使用栈辅助完成。此外,还探讨了二叉搜索树(BST)的迭代器实现,包括两种不同复杂度和内存占用的解决方案。
3万+

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



