二叉樹的最小深度

題目

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

java實現

public int run(TreeNode root) {
        if (root == null)//空樹深度爲0
            return 0;
        if (root.left == null && root.right == null)//只有一個節點
            return 1;
        int leftDepth = run(root.left);
        int rightDepth = run(root.right);
        if (leftDepth == 0)//左子樹深度爲0,返回右子樹深度加1
            return rightDepth + 1;
        else if (rightDepth == 0)
            return leftDepth + 1;
        else
            return Math.min(leftDepth, rightDepth) + 1;
    }
發佈了113 篇原創文章 · 獲贊 19 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章