二叉树进阶算法题
文章目录
- 二叉树进阶算法题
- 606. 根据二叉树创建字符串
- 102. 二叉树的层序遍历
- 107. 二叉树的层序遍历 II
- 总结
606. 根据二叉树创建字符串
代码如下(示例):
class Solution{public:stringtree2str(TreeNode*root){string res;if(root==nullptr)returnres;res+=to_string(root->val);// 表示两种情况// 左为空,右不为空 和 左不为空if(root->left||root->right){res+='(';res+=tree2str(root->left);res+=')';}// 右不为空if(root->right){res+='(';res+=tree2str(root->right);res+=')';}returnres;}};102. 二叉树的层序遍历
代码如下(示例):
class Solution{public:vector<vector<int>>levelOrder(TreeNode*root){vector<vector<int>>result;if(root==nullptr)returnresult;queue<TreeNode*>st;st.push(root);while(!st.empty()){intsz=st.size();vector<int>littleresult;for(inti=0;i<sz;i++){TreeNode*top=st.front();st.pop();littleresult.push_back(top->val);if(top->left)st.push(top->left);if(top->right)st.push(top->right);}result.push_back(littleresult);}returnresult;}};107. 二叉树的层序遍历 II
这道题就是在上一道题的基础上面加上了一个逆序!
代码如下(示例):
class Solution{public:vector<vector<int>>levelOrderBottom(TreeNode*root){vector<vector<int>>result;if(root==nullptr)returnresult;queue<TreeNode*>st;st.push(root);while(!st.empty()){intsz=st.size();vector<int>littleresult;for(inti=0;i<sz;i++){TreeNode*top=st.front();st.pop();littleresult.push_back(top->val);if(top->left)st.push(top->left);if(top->right)st.push(top->right);}result.push_back(littleresult);}reverse(result.begin(),result.end());returnresult;}};总结
这篇文章是作者搜集大量面经和资料这里出来的。感谢你的支持
作者wkm是一名中国矿业大学(北京) 大一的新生,希望得到你的关注
如果可以的话,记得一键三联!