이진 트리의 최소 깊이 실제 이진 트리 알고리즘

이름

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