The minimum depth of a binary tree] [Leetcode

 

Given a binary tree, to find out the minimum depth.

Minimum depth is the number of nodes in the shortest path from the root node to leaf nodes nearest .

Depth-based recursive search algorithm.

Depth of the search: First of all find out from the path of the root node to the leaf node , and then compare the minimum depth.

Recursive: need to define recursive functions .

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL)
            return 0;
        
        int result = 0, left = 0, right = 0;
        left = minDepth(root->left);
        right = minDepth(root->right);

        if (left == 0 || right == 0)
            result = 1 + max(left, right);
        else
            result  = 1 + min(left, right);
        
        return result;
    }
};

 

Complexity analysis:

Time complexity: number of nodes is N. Each node visited once, O (n).

Space complexity: the worst case, N nodes constitute unbalanced tree, each node has only one child, this time a recursive call N times (height of the tree), then stack space overhead is O (n) the most. Ideally, N nodes constituting a perfectly balanced tree, the tree is logN height, stack space overhead is O (logN).

 

Guess you like

Origin www.cnblogs.com/gdut-gordon/p/11371900.html