104. Maximum Depth of Binary Tree

這題我今天做contest的時候突然想起來,可以遍歷一遍來做。。感覺時間復(fù)雜度跟經(jīng)典的三行做法是一樣的O(n)。。不過代碼很冗長。

My code

        int max = 0;

    public int maxDepth(TreeNode root) {
        traverse(root, 1);
        return max;
    }

    private void traverse(TreeNode root, int lvl) {
        if (root == null) return;
        max = Math.max(lvl, max);
        traverse(root.left, lvl + 1);
        traverse(root.right, lvl + 1);
    }

三行做法:

public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
// + 1代表根節(jié)點
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

iteration 做法

如果做minimum depth,用這個方法復(fù)雜度低。

    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        //本層的node數(shù)
        int curNum = 1;
        //下一層的node數(shù)
        int nextNum = 0;
        int level = 0;
        LinkedList<TreeNode> linkedList = new LinkedList<>();
        linkedList.add(root);
        while (linkedList.size() != 0) {
            TreeNode node = linkedList.poll();
            curNum--;
            if (node.left != null) {
                linkedList.add(node.left);
                nextNum++;
            }

            if (node.right != null) {
                linkedList.add(node.right);
                nextNum++;
            }

            if (curNum == 0) {
                level++;
                curNum = nextNum;
                nextNum = 0;
            }
        }
        return level;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容