バイナリツリーの最小深実際のバイナリツリーアルゴリズム

タイトル

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が返されます。

  2. そうでない場合は、リーフノード、および再帰的に左のサブツリーがnullの場合、右のサブツリー。

  3. ないリーフノードと右部分木がnullの場合は、再帰的に左のサブツリー。

  4. そうでない場合は、リーフノード、および左右の部分木の再帰後に撮影した小さな値がnull少ないです。

概要

  • ツリートラバーサルの各ノードので、時間計算量はO(N)です。

  • もちろん、このような方法階層トラバーサルなどの他の良いアイデアは、リーフノードの深さの最初の出会いを返し、があります。

GitHubDemoのリソース

github.com/renmoqiqi/1...

ます。https://juejin.im/post/5cfdb625f265da1baf7cdfcdで再現

おすすめ

転載: blog.csdn.net/weixin_34289744/article/details/91432472