[Leetcode in Java] 515. Find Largest Value in Each Tree Row


Posted by LarsonKao on 2022-05-26

515. Find Largest Value in Each Tree Row

Link

難易度 : Medium

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

question

這題一樣是要在遍尋每層node的過程中記錄每層最大的val,也是大致相同的做法。

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

result


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







Related Posts

【Day 2】Docker Image (映像檔) & Dockerfile

【Day 2】Docker Image (映像檔) & Dockerfile

Day00-Lavarel新手接觸

Day00-Lavarel新手接觸

【隨堂筆記】Python函式、類別與物件

【隨堂筆記】Python函式、類別與物件


Comments