Leetcode102
1.问题描述
2.解决方案
注意点:
1.需要三个数据结构
vector<vector<int>> ans;
queue<TreeNode*> queue;
vector<int> oneLayer;
2.一定要用固定大小len,用来表示一层一层处理,而不是queue.size(),因为queue.size()是不断变化的
int len=queue.size();
for(int i=0;i<len;i++)
代码实现:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> queue;
queue.push(root);
if(root==nullptr) return ans;
while(queue.empty()== false){
vector<int> oneLayer;
int len=queue.size();
for(int i=0;i<len;i++){
TreeNode* cur=queue.front();
queue.pop();
oneLayer.push_back(cur->val);
if(cur->left!= nullptr) queue.push(cur->left);
if(cur->right!= nullptr) queue.push(cur->right);
}
ans.push_back(oneLayer);
}
return ans;
}
};
Leetcode107
1.问题描述
2.解决方案
比正常的层序遍历也就是102题,只多了下面这一行,把ans反转一下就好了!
reverse(ans.begin(),ans.end()); //只比102层序遍历多了这一行
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> queue;
queue.push(root);
if(root==nullptr) return ans;
while(queue.empty()== false){
vector<int> oneLayer;
int len=queue.size();
for(int i=0;i<len;i++){
TreeNode* cur=queue.front();
queue.pop();
oneLayer.push_back(cur->val);
if(cur->left!= nullptr) queue.push(cur->left);
if(cur->right!= nullptr) queue.push(cur->right);
}
ans.push_back(oneLayer);
}
reverse(ans.begin(),ans.end()); //只比102层序遍历多了这一行
return ans;
}
};
BM27.按之字形顺序打印二叉树
1.问题描述
2.解决方案
1.正常一层一层的层序遍历,用len去控制每一层
2.如果遇到需要反转的,就调用swapList做一个反转,然后加入结果集就可以
import java.util.*;
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void swapList(ArrayList<Integer> list){
int left = 0;
int right = list.size()-1;
while(left<=right){
Integer t = list.get(left);
list.set(left, list.get(right));
list.set(right, t);
left++;
right--;
}
}
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > ans = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
if(pRoot==null) return ans;
queue.addLast(pRoot);
int cnt = 1;
while(queue.size()!=0){
int len = queue.size();
ArrayList<Integer> layer = new ArrayList<>();
for(int i=0;i<len;i++){
TreeNode t = queue.removeFirst();
layer.add(t.val);
if(t.left!=null) queue.addLast(t.left);
if(t.right!=null) queue.addLast(t.right);
}
//转换从左到右 为 从右到左
if(cnt++%2==0) swapList(layer);
ans.add(layer);
}
return ans;
}
}