Binary Tree Level Order Traversal II,binarytraversal

來源:互聯網
上載者:User

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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.