Minimum Depth of Binary Tree

//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.

//求二叉樹的最小深度,與求最大深度非常類似,但需要增加左右子樹的判斷,因爲如果一個節點如果只有左子樹或者右子樹,我們不能取它左右子樹中小的作爲深度,因爲那樣會是0,我們只有在葉子節點才能判斷深度,而在求最大深度的時候,因爲一定會取大的那個,所以不會有這個問題

public int minDepthOfBT(TreeNode root)

{
        if(null == root)

        {
            return 0;
        }
        int _left = run(root.left);
        int _right = run(root.right);

        if(_left == 0 || _right == 0)

        {
            return 1 + _left + _right;
        }
        return _left <= _right ? 1 + _left : 1 + _right;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章