[Leetcode in Java] 107. Binary Tree Level Order Traversal II


Posted by LarsonKao on 2022-05-26

107. Binary Tree Level Order Traversal II

Link

難易度 : Medium

依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :

question

這題跟[102]一樣,只是要求倒序的列出,因此程式上最後在reverse即可。

    class Solution
    {
        public List<List<Integer>> levelOrderBottom(TreeNode root)
        {
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            TreeNode current;
            if(root==null) 
            {
                return result;
            }
            queue.add(root);
            while(!queue.isEmpty()) 
            {
                int size = queue.size();
                List<Integer> tuple = new ArrayList<Integer>();
                //遍尋此層數量的所有node 之後加入的不與理會
                for(int i=0;i<size;i++) 
                {
                    current = queue.poll();
                    tuple.add(current.val);
                    if(current.left!=null) 
                    {
                        queue.add(current.left);
                    }
                    if(current.right!=null) 
                    {
                        queue.add(current.right);
                    }
                }
                if(tuple.size()>0) 
                {
                    result.add(tuple);
                }
            }
            Collections.reverse(result);
            return result;
        }
    }

result


#Leetcode #java #algorithm #Queue #binary tree #BFS







Related Posts

Vue 2 與 Vue 3 的不同

Vue 2 與 Vue 3 的不同

網路溝通、HTTP 協定

網路溝通、HTTP 協定

Android Kotlin-1 基本語法1

Android Kotlin-1 基本語法1


Comments