LeetCode 107.Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
题意:给定一个二叉树,从叶子结点开始,从左往右,从上往下地返回二叉树中的所有结点。
思路:层次遍历,建立一个queue,先将根节点放进去,用while循环判断queue是否为空,不为空时,建立一个存放结点数值的链表,获取当前queue的结点个数,建立for循环,将当前结点的值val放入新链表中,再判断当前结点的左右子树是否为空,不为空则将子树存入queue。for循环结束后,将存放结点数值的链表存入list的首位。
代码如下:
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> list = new LinkedList<List<Integer>>(); if (root == null) return list; Queue<TreeNode> subList = new LinkedList<>(); int size = 0; subList.add(root); while (!subList.isEmpty()) { List<Integer> subListInt = new LinkedList<>(); size = subList.size();// 判断当前层中结点个数 for (int i = 0; i < size; i++) { TreeNode t = subList.poll();//获取并移除此队列的头元素 subListInt.add(t.val);// 存入当前结点的值val if (t.left != null)// 将下一层的结点存入链表中 subList.add(t.left); if (t.right != null) subList.add(t.right); } ((LinkedList<List<Integer>>) list).addFirst(subListInt); } return list; }