Minimum Depth actual binary tree algorithm of a Binary Tree

topic

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.
复制代码

The main code

- (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;

}
复制代码

Thinking

  1. Each node binary tree traversal, if the current node is a leaf node, 1 is returned.

  2. If not a leaf node, and the left subtree is null, then the right subtree recursively.

  3. If not a leaf node and the right subtree is null, then recursively the left subtree.

  4. If not a leaf node, and the left and right subtrees are less the smaller value taken after recursion is null.

summary

  • Since each node in the tree traversal, the time complexity is O (n).

  • Of course there are other good ideas, such as the method hierarchy traversal, returns the first encounter of the depth of the leaf nodes.

GitHubDemo resources

github.com/renmoqiqi/1…

Reproduced in: https: //juejin.im/post/5cfdb625f265da1baf7cdfcd

Guess you like

Origin blog.csdn.net/weixin_34289744/article/details/91432472