[leetcode]Binary Tree Level Order Traversal II

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   io   for   

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,#,#,15,7},

    3   /   9  20    /     15   7

 

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]] 

演算法思路:

典型的BFS,與[leetcode]Binary Tree Level Order Traversal完全一樣,不過一個是對list的頭插,一個是尾插法。

代碼如下:

 1 public class Solution { 2     public List<List<Integer>> levelOrderBottom(TreeNode root) { 3         List<List<Integer>> res = new LinkedList<List<Integer>>(); 4         if(root == null) return res; 5         Queue<TreeNode> q = new LinkedList<TreeNode>(); 6         Queue<TreeNode> copy = new LinkedList<TreeNode>(); 7         q.offer(root); 8         res.add(new ArrayList<Integer>(Arrays.asList(root.val))); 9         while(!q.isEmpty()){10             TreeNode node = q.poll();11             if(node.left != null) copy.offer(node.left);12             if(node.right != null) copy.offer(node.right);13             if(q.isEmpty() && !copy.isEmpty()){14                 List<Integer> list = new ArrayList<Integer>();15                 while(!copy.isEmpty()){16                     q.offer(copy.peek());17                     list.add(copy.poll().val);18                 }19                 res.add(0,list);20             }21         }22         return res;23     }24 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.