1. 程式人生 > >LeetCode 107.Binary Tree Level Order Traversal II

LeetCode 107.Binary Tree Level Order Traversal II

spa values 個數 -s 判斷 ret 層次遍歷 pub ger

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

 

LeetCode 107.Binary Tree Level Order Traversal II