二叉樹的算法實戰 Minimum Depth of a 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.
複製代碼

主要代碼

- (int)minimumDepth:(DSTreeNode *)root
{
    //1
    if (root == nil) {
        return 0;
    }
    //2
    if (root.leftChild == nil) {
        return [self minimumDepth:root.rightChild]+1;

    }
    //3
    if (root.rightChild == nil) {
        return [self minimumDepth:root.leftChild]+1;

    }
    //4
    return MIN([self minimumDepth:root.leftChild], [self minimumDepth:root.rightChild])+1;

}
複製代碼

思路

  1. 遍歷二叉樹的每一個節點,若是當前節點是葉子節點,則返回1。node

  2. 若是不是葉子節點,且左子樹爲null,而後遞歸右子樹。git

  3. 若是不是葉子節點且右子樹爲null,而後遞歸左子樹。github

  4. 若是不是葉子節點,且左右子樹不爲null那麼取遞歸後二者最小值。bash

小結

  • 因爲遍歷樹的每一個節點,所以時間複雜度是O(n)。ui

  • 固然還有其餘不錯的思路好比用層級遍歷的方法,返回第一個遇到葉子節點的深度。spa

GitHubDemo資源

github.com/renmoqiqi/1…3d

相關文章
相關標籤/搜索