[LeetCode] minimum depth binary tree

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.

Description: leaf node is a node has no child nodes.

Example:

Given binary tree [3,9,20, null, null, 15,7],

    3
   / \
  920
    / \
   157
returns to its minimum depth 2.

BFS:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> q{{root}};
        int level = 0;
        while(!q.empty())
        {
            level++;
            for(int i = q.size();i > 0;i--)
            {
                TreeNode* t = q.front();q.pop();
                if(!t->left && !t->right)
                    return level;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }

        return -1;
    }
};

Recursion:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        if (!root->left) return 1 + minDepth(root->right);
        if (!root->right) return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};

DFS: Stack

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        stack<pair<TreeNode*,int>> ss;
        ss.push(make_pair(root,1));
        int res = INT_MAX;

        while(!ss.empty())
        {
            TreeNode * t = ss.top().first;
            int level = ss.top().second;
            ss.pop();

            if(!t->left && !t->right)
            {
                res = min(level,res);
            }

            if(t->left)
                ss.push(make_pair(t->left,level + 1));
            if(t->right)
                ss.push(make_pair(t->right,level + 1));
        }
        return res;
    }
};

 

Published 116 original articles · won praise 2 · Views 7649

Guess you like

Origin blog.csdn.net/weixin_37992828/article/details/104092494