1.LEETCODE102
二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
解题思路:
1.逐层添加到队列
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
class Solution {
//层次遍历采用队列实现
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root == null)
return list;
//层次遍历
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(true){
Queue<TreeNode> temp = new LinkedList<>();
List<Integer> tempList = new ArrayList<>();
while(!queue.isEmpty()){
TreeNode t = queue.poll();
tempList.add(t.val);
if(t.left!=null)
temp.add(t.left);
if(t.right!=null)
temp.add(t.right);
}
list.add(tempList);//自顶向下输出
if(temp.isEmpty())
break;
queue = temp;
}
return list;
}
}
2.LEETCODE107
二叉树的层次遍历 II
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root == null)
return list;
//层次遍历
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(true){
Queue<TreeNode> temp = new LinkedList<>();
List<Integer> tempList = new ArrayList<>();
while(!queue.isEmpty()){
TreeNode t = queue.poll();
tempList.add(t.val);
if(t.left!=null)
temp.add(t.left);
if(t.right!=null)
temp.add(t.right);
}
list.add(0,tempList);//自底向上输出
if(temp.isEmpty())
break;
queue = temp;
}
return list;
}
}
---------------------
作者:长弓Smile
来源:CSDN
原文:https://blog.csdn.net/u012485480/article/details/80762275
版权声明:本文为博主原创文章,转载请附上博文链接!