【Leetcode】111. Minimum Depth of Binary Tree(二叉树最小深度)

版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89416496

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.

Example:

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

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

题目大意:

求出二叉树最小深度,深度被定义为从根节点到最近的叶节点的最短路径上的节点数。

解题思路:

遍历到根节点时判断全局的最小深度和当前深度的最小值。

/**
 * 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 {
    
private:
    int ans;
    
    int helper(TreeNode *tmp, int deeper){
        if(tmp->right==NULL&&tmp->left==NULL){
            return ans==-1? deeper : min(deeper,ans);
        }
        if(tmp->left!=NULL){
            ans = helper(tmp->left, deeper+1);
        }
        if(tmp->right!=NULL){
            ans = helper(tmp->right, deeper+1);
        }
        return ans;
        
    }
    
public:
    int minDepth(TreeNode* root) {
        ans= -1;
        return root ? helper(root,1) : 0;
        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_29600137/article/details/89416496