107. 二叉树的层序遍历 II(简单)
给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层序遍历为:
1 2 3 4 5
| [ [15,7], [9,20], [3] ]
|
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
思路1:
常规BFS
代码1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(root==null){ return res; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()){ List<Integer> list = new ArrayList<>(); int size = queue.size(); for(int i =0;i<size;i++){ TreeNode node = queue.poll(); list.add(node.val); TreeNode left = node.left; TreeNode right = node.right; if(left!=null){ queue.offer(left); } if(right!=null){ queue.offer(right); } } res.add(0,list); } return res; } }
|