[Leetcode in Java] 111. Minimum Depth of Binary Tree


Posted by LarsonKao on 2022-05-26

111. Minimum Depth of Binary Tree

Link

難易度 : Easy

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

question

這題與前一題相反,要求找出最淺的深度,邏輯的話跟前一題很類似,但只要遇到node都沒有子節點就可以直接return當前的深度了。

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

result


#Leetcode #java #algorithm #binary tree







Related Posts

[Note] JS: OOP - Inheritance

[Note] JS: OOP - Inheritance

MTR04_1103

MTR04_1103

[Oracle SQL Debug] 解決ORA-01489的問題

[Oracle SQL Debug] 解決ORA-01489的問題


Comments