给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我自己对树的相关操作还是比较差劲,这个题目我想到的是使用广度优先搜索,方向是没有错的,但是代码有问题,所以最终没有写出来,在看了题解之后,理解思路之后再写了一遍将代码写出来了。
思路是:将树的父结点先加入队列中,然后移除,判断移除的父结点的左右结点是否存在,通过for循环将同一层的所有子结点加入队列中,直到遍历完树
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null){
return new ArrayList<>();
}
List<List<Integer>> list = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
List<Integer> list1 = new ArrayList<>();
//这里需要注意,必须使用size变量,否则在for循环中queue.size()是变化的
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode first = queue.removeFirst();
list1.add(first.val);
if (first.left != null){
queue.add(first.left);
}
if (first.right != null){
queue.add(first.right);
}
}
list.add(0,list1);
}
return list;
}