企业微信网站怎么做的,关于申请网站建设,网站模板去哪要,水处理网站模板#x1f4d8;北尘_#xff1a;个人主页 #x1f30e;个人专栏:《Linux操作系统》《经典算法试题 》《C》 《数据结构与算法》 ☀️走在路上#xff0c;不忘来时的初心 文章目录 一、根据二叉树创建字符串1、题目讲解2、思路讲解3、代码实现 二、二叉树的分层遍历1、题目讲… 北尘_个人主页 个人专栏:《Linux操作系统》《经典算法试题 》《C》 《数据结构与算法》 ☀️走在路上不忘来时的初心 文章目录 一、根据二叉树创建字符串1、题目讲解2、思路讲解3、代码实现 二、二叉树的分层遍历1、题目讲解2、思路讲解3、代码实现 三、二叉树的最近公共祖先1、题目讲解2、思路讲解递归展开图3、代码实现 一、根据二叉树创建字符串
1、题目讲解 2、思路讲解 3、代码实现
class Solution {
public:string tree2str(TreeNode* root) {string s;if(rootnullptr)return s;sto_string(root-val);if(root-left || (root-leftnullptr root-right)){s(;stree2str(root-left);s);}if(root-right){s(;stree2str(root-right);s);}return s;}
};二、二叉树的分层遍历
1、题目讲解 2、思路讲解 3、代码实现
class Solution {
public:vectorvectorint levelOrder(TreeNode* root) {queueTreeNode* s;vectorvectorint vv;int levelsize;if(root){s.push(root);levelsize1;}while(!s.empty()){vectorint v;while(levelsize--){TreeNode* fronts.front();s.pop();v.push_back(front-val);if(front-left)s.push(front-left);if(front-right)s.push(front-right); }vv.push_back(v);levelsizes.size();}return vv;}
};三、二叉树的最近公共祖先
1、题目讲解 2、思路讲解递归展开图 思路一 思路二 3、代码实现 代码一 class Solution {
public:bool find(TreeNode* root,TreeNode* x){if(rootnullptr)return false;if(rootx)return true;return (find(root-left,x)||find(root-right,x));}TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(rootp || rootq)return root;bool pleftfind(root-left,p);bool pright!pleft;bool qleftfind(root-left,q);bool qright!qleft;if((pleft qright) || (pright qleft)){return root;}if(pleft qleft){return lowestCommonAncestor(root-left,p,q);}if(pright qright){return lowestCommonAncestor(root-right,p,q);}return nullptr;}
};代码二 class Solution {
public:bool findpath(TreeNode* root,TreeNode* x,stackTreeNode* st){if(rootnullptr)return false;st.push(root);if(rootx)return true;if(findpath(root-left,x,st))return true;if(findpath(root-right,x,st))return true;st.pop();return false; }TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {stackTreeNode* ppath,qpath;findpath(root,p,ppath);findpath(root,q,qpath);while(ppath.size()!qpath.size()){if(ppath.size()qpath.size())ppath.pop();elseqpath.pop();}while(ppath.top()!qpath.top()){ppath.pop();qpath.pop();}return qpath.top(); }
};