1. 程式人生 > >LeetCode刷題Easy篇Binary Tree Level Order Traversal II

LeetCode刷題Easy篇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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its bottom-up level order traversal as:

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

我的解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
         List<List<Integer>> list=new LinkedList();
        if(root==null) return list;
        Deque<TreeNode> queue=new LinkedList();
        queue.add(root);
        List<Integer> rootList=new LinkedList();
        rootList.add(root.val);
        list.add(rootList);
        while(!queue.isEmpty()){
            int size=queue.size();
            List<Integer> subList=new LinkedList();
            while(size-->0){
               TreeNode treeNode=queue.poll();
               if(treeNode.left!=null){
                queue.add(treeNode.left);
                subList.add(treeNode.left.val);
                }
                if(treeNode.right!=null){
                queue.add(treeNode.right);
                subList.add(treeNode.right.val);
                } 
            } 
            if(subList.size()>0){
                 list.add(0,subList);
            }
           
        }
        return list;
    }
}

最優解法

最優解法就是我的解法。唯一可以優化的地方是,把root新增到list,和left,right可以合併一句 程式碼,另外,一定用linkedlist,因為需要add(0,list),如果用arraylist效率低

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
         List<List<Integer>> list=new LinkedList();
        if(root==null) return list;
        Deque<TreeNode> queue=new LinkedList();
        queue.add(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            List<Integer> subList=new LinkedList();
            while(size-->0){
               TreeNode treeNode=queue.poll();
                //處理來的不可能為空,因為入queue會判斷
                subList.add(treeNode.val);
               if(treeNode.left!=null){
                  queue.add(treeNode.left);
                }
                if(treeNode.right!=null){
                queue.add(treeNode.right);
                } 
            } 
          list.add(0,subList);  
        }
        return list;
    }
}