Binary Tree Level Order Traversal II,binarytraversal
本文是在學習中的總結,歡迎轉載但請註明出處: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.
OJ's Binary Tree Serialization:
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 \ 5
The 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為空白時不能返回nullif (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;}