[Leetcode in Java] 104. Maximum Depth of Binary Tree


Posted by LarsonKao on 2022-05-26

104. Maximum Depth of Binary Tree

Link

難易度 : Easy

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

question

題目要求找出binary tree的最大深度,先使用模板來解題吧!

    class Solution
    {
        public int maxDepth(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) 
                    {
                        queue.add(current.left);
                    }
                    if(current.right!=null) 
                    {
                        queue.add(current.right);
                    }
                }
            }
            return depth;
        }
    }

result

但是同樣的看得出來,效率很差勁,因此看了一下discuss的做法,直接用簡單的recursive來做就可以快得非常多!
code非常簡單,應該很容易就能看懂

    class Solution
    {
        public int maxDepth(TreeNode root)
        {
            if(root==null) 
            {
                return 0;
            }

            return 1+(Math.max(maxDepth(root.left), maxDepth(root.right)));
        }
    }

result2


#Leetcode #java #algorithm #Queue #binary tree







Related Posts

七天帶你初探AR世界-Day 2

七天帶你初探AR世界-Day 2

如何完成程式設計共學營報名流程?

如何完成程式設計共學營報名流程?

JavaScript 核心 - Event Loop

JavaScript 核心 - Event Loop


Comments