您的位置:首页 > 娱乐 > 明星 > 策划书_怎样开网店详细步骤_优化设计答案大全_网站设计模板

策划书_怎样开网店详细步骤_优化设计答案大全_网站设计模板

2025/2/25 18:07:35 来源:https://blog.csdn.net/qq_74420726/article/details/145539143  浏览:    关键词:策划书_怎样开网店详细步骤_优化设计答案大全_网站设计模板
策划书_怎样开网店详细步骤_优化设计答案大全_网站设计模板

递归算法

三要素

  • 参数和返回值
  • 终止条件
  • 单层返回逻辑

例题

leetcode:

  • 144.二叉树的前序遍历(opens new window)
  • 145.二叉树的后序遍历(opens new window)
  • 94.二叉树的中序遍历

迭代遍历

递归的本质还是利用栈实现的,所以我们可以配合栈来实现迭代遍历

前序遍历

先压入root;

root出栈时,压入右左节点,然后重复该过程直到栈空。

class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {vector<int> res;stack<TreeNode*> Mysta;if(root)Mysta.push(root);while(!Mysta.empty()){TreeNode* cur=Mysta.top();Mysta.pop();if(cur->right)Mysta.push(cur->right);if(cur->left)Mysta.push(cur->left);res.push_back(cur->val);}return res;}};

中序遍历

中序遍历不能直接改编前序遍历;

把左边一支全部压栈;

然后吐出栈顶为cur,处理完后,将当cur的右节点以及左边的一支压入

class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int> res;stack<TreeNode*> Mysta;TreeNode* cur=root;while(cur){Mysta.push(cur);cur=cur->left;            }while(!Mysta.empty()){cur=Mysta.top();Mysta.pop();if(cur->right){TreeNode* tmp=cur->right;while(tmp){Mysta.push(tmp);tmp=tmp->left;}}res.push_back(cur->val);}return res;}
};

后序遍历

后序遍历可以通过镜像的先序遍历,然后反转整个结果得到。

class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int> res;stack<TreeNode*> stack;if(root)stack.push(root);while(!stack.empty()){TreeNode* cur=stack.top();stack.pop();res.push_back(cur->val);if(cur->left)stack.push(cur->left);if(cur->right)stack.push(cur->right);}reverse(res.begin(),res.end());return res;}
};

统一迭代

层序遍历

队列

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com