这十道题都有些相似,以下是选做。
挺简单的
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int size = 1;
while(!q.isEmpty()){
List<Integer> ls = new ArrayList<>();
int count = 0;
for(int i = 0; i < size; ++i){
TreeNode tmp = q.remove();
ls.add(tmp.val);
if(tmp.left != null) {q.offer(tmp.left); ++count;}
if(tmp.right != null) {q.offer(tmp.right); ++count;}
}
size = count;
res.add(ls);
}
return res;
}
}
这个右视图是必须遍历一遍才可以的,偷懒是做不出来的。
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root == null) return res;
q.add(root);
int size = 1;
while(!q.isEmpty()){
int count = 0;
for(int i = 0; i < size; ++i){
TreeNode tmp = q.remove();
if(tmp.left != null){ q.add(tmp.left); ++count;}
if(tmp.right != null){ q.add(tmp.right); ++count;}
if(i == size-1){res.add(tmp.val);}
}
size = count;
}
return res;
}
}
吊题,不难!
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int size = 1;
while(!q.isEmpty()){
int count = 0;
double avg = 0;
for(int i = 0; i < size; ++i){
TreeNode tmp = q.remove();
avg += (double) tmp.val;
if(tmp.left != null){q.add(tmp.left); ++count;}
if(tmp.right != null){q.add(tmp.right); ++count;}
}
avg /= (double) size;
res.add(avg);
size = count;
}
return res;
}
}
照葫芦画瓢。
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
int size = 1;
while(!q.isEmpty()){
int count = 0;
List<Integer> subList = new ArrayList<>();
for(int i = 0; i < size; ++i){
Node tmp = q.remove();
subList.add(tmp.val);
for(int j = 0; j < tmp.children.size(); ++j){
q.add(tmp.children.get(j));
++count;
}
}
res.add(subList);
size = count;
}
return res;
}
}
这两题是十题之外的,但我感觉都很简单。我觉得这两题掌握iteration方法是没有意义的,因为空间上,用iteration的效果非常差。
5.翻转二叉树
之前见过一遍,再见的时候就不觉得怪/写不出来了。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
TreeNode* tmp = root;
swap(tmp->left, tmp->right);
invertTree(tmp->left);
invertTree(tmp->right);
return root;
}
};
6.对称二叉树
怎么简洁地查条件是这题的精髓。
class Solution {
private boolean helper(TreeNode l, TreeNode r){
if(l == null && r == null) return true;
if(l == null || r == null) return false;
if(l.val != r.val) return false;
return helper(l.right, r.left) && helper(l.left, r.right);
}
public boolean isSymmetric(TreeNode root) {
return helper(root.left, root.right);
}
}
二叉树与N叉树遍历技巧
本文介绍并实现了二叉树及N叉树的层序遍历算法,包括基本的层序遍历、右视图遍历、每层平均值计算等,并提供了翻转二叉树和判断对称性的简洁实现。
1031

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



