本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41964067
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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
思路:
(1)题意为按层次从树顶到树根输出每层元素,该题和(Binary Tree Level Order Traversal)按层次从树根到树顶输出每层元素思路一样。
(2)只需要将Binary Tree Level Order Traversal得到的链表逆序即为本题答案。
详细过程请参照http://blog.csdn.net/pistolove/article/details/41929059。
(3)希望对你有所帮助。谢谢。
算法代码实现如下所示:
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> result = new LinkedList<List<Integer>>(); // 注意root为空时不能返回null if (root == null) return result; List<TreeNode> all = new LinkedList<TreeNode>(); all.add(root); int first = 0; // 当前待访问节点,初始为第一个节点,即根节点 int last = 1; // 当前链表中元素个数,初始只有一个 while (first < all.size()) { // 如果待访问节点存在于链表 last = all.size(); // 下一行访问开始,定位last为当前行最后一个节点下一个节点所在位置 List<Integer> level = new LinkedList<Integer>(); while (first < last) { // 如果first==last表示该行所有节点都被访问到了,跳出循环 level.add(all.get(first).val); if (all.get(first).left != null) { all.add(all.get(first).left); } if (all.get(first).right != null) { all.add(all.get(first).right); } first++; // 每访问完一个节点就指向下一个节点 } result.add(level); } //链表逆序 和按层次打印思路一样 List<List<Integer>> fina = new LinkedList<List<Integer>>(); for (int i = result.size() - 1; i >= 0; i--) { fina.add(result.get(i)); } return fina; }