LeetCode:二叉树的层次遍历||【107】
题目描述
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3] ]
题目分析
依然是二叉树的层次遍历,采取BFS算法,最后的逆序只是一个小插曲而已。
Java题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> line = new ArrayList<>();
if(root == null)
return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
line.add(root.val);
ans.add(line);
line = new ArrayList<>();
int size = queue.size();
int flag = 1;
while(!queue.isEmpty())
{
TreeNode tmp = queue.poll();
if(tmp.left!=null)
{
queue.add(tmp.left);
line.add(tmp.left.val);
}
if(tmp.right!=null)
{
queue.add(tmp.right);
line.add(tmp.right.val);
}
size--;
if(size==0&&line.size()>0)
{
size=queue.size();
ans.add(line);
line = new ArrayList<>();
}
}
Collections.reverse(ans);
return ans;
}
}