zoukankan      html  css  js  c++  java
  • [LeetCode] Minimum Depth of Binary Tree

    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.

    我记得有一题是叫算Max depth 的,如出一辙。思路就是拿到一颗树,分别算出他左右子树的min depth,然后返回其中最小的那个+1就行了。

    但是要注意的是和max depth有区别的地方在于,要判断左右子树存不存在先,如果不存在就忽略了。

    int minDepth(TreeNode *root) {
        if (!root) return 0;
        if (!root->left && !root->right) return 1;
        
        int leftMin = INT_MAX;
        int rightMin = INT_MAX;
        
        if (root->left)
            leftMin = minDepth(root->left);
        if (root->right)
            rightMin = minDepth(root->right);
        
        return leftMin < rightMin ? leftMin+1 : rightMin+1;
    }
  • 相关阅读:
    指针2
    学习笔记day3
    学习笔记day2
    学习笔记day1
    lighttpd启用支持IPv6
    GPL/widedhcpv6/dhcp6c源代码分析
    有多个vsftpd进程运行
    Java学习笔记day1
    python_day4
    python_day3.2
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4094179.html
Copyright © 2011-2022 走看看