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

Note: A leaf is a node with no children.

原題鏈接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

解題思路

遞歸,主要需要考慮一種特殊情況即某個子樹的根節點僅有左孩子或者僅有右孩子,此時這個子樹的最小深度應當是該子樹根節點存在的子樹(可能是左子樹存在也可能是右子樹存在)的最小深度加一。

方案一

執行用時 : 44 ms 內存消耗 : 19.7 MB

 class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        // 當左右子樹均不爲空時return1 + min(left, right)
        //當左右子樹其中之一爲空時return 1+ left + right 此時left和right中 
        return (left && right) ? 1+min(left, right): 1+left+right;
        }
};

方案二

寫的詳細點可能更好理解,將所有情況都列出來。
執行用時 : 32ms 內存消耗 : 19.3 MB

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        if(!root->left && !root->right)
            return 1;
        else if(!root->left)
            return minDepth(root->right)+1;
        else if(!root->right)
            return minDepth(root->left)+1;
        else{
        return minDepth(root->left) > minDepth(root->right)? minDepth(root->right)+1:minDepth(root->left)+1;
        }
        }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章