1. 程式人生 > >leetcode111題 題解 翻譯 C語言版 Python版

leetcode111題 題解 翻譯 C語言版 Python版

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.

111.二叉樹的最小深度

給定一棵二叉樹,求其最小深度

最小深度是指從根結點到最近的葉結點的最短路徑經過的結點數。

思路:用遞迴可以很方便的解決問題。如果當前是葉結點,那麼直接返回1表示深度為1。如果當前不是葉結點,那麼先遞迴得到左右子樹分別的最小深度,然後用其較小值加1返回就表示當前結點領頭的樹的最小深度了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int minDepth(struct TreeNode* root) {
    if (!root) return 0;
    if (!root->left && !root->right) return 1;
    if (!root->left) return minDepth(root->right) + 1;
    if (!root->right) return minDepth(root->left) + 1;
    int minleft = minDepth(root->left);
    int minright = minDepth(root->right);
    return minleft < minright ? minleft + 1 : minright + 1;
}


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        if not (root.left or root.right): return 1
        if not root.left: return self.minDepth(root.right) + 1
        if not root.right: return self.minDepth(root.left) + 1
        minleft, minright = self.minDepth(root.left), self.minDepth(root.right)
        return minleft+1 if minleft < minright else minright+1