zoukankan      html  css  js  c++  java
  • leetcode-111. 二叉树最小深度 · Tree + 递归

    题面

    找出二叉树的最小深度(从根节点到某个叶子节点路径上的节点个数最小)。

    算法

    算法参照二叉树的最大深度,这里需要注意的是当某节点的左右孩子都存在时,就返回左右子树的最小深度如果不都存在,就需要返回左右子树的最大深度(因为子节点不存在的话,通向该子树的路径就走不同,就不存在深度,也无法比较。只能从另一子树方向走。)如果左右孩子不都存在时还取小值,那返回的就是父节点的深度,会出错。

    源码 

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode* root) {
     4         if(root == nullptr)
     5             return 0;
     6         if(root->left && root->right)
     7             return min(getDepth(root->left, 1), getDepth(root->right, 1));
     8         else
     9             return max(getDepth(root->left, 1), getDepth(root->right, 1));
    10     }
    11     
    12     int getDepth(TreeNode* p, int deep)
    13     {
    14         if(p == nullptr)
    15             return deep;
    16         if(p->left && p->right)
    17             return min(getDepth(p->left, deep+1), getDepth(p->right, deep+1));
    18         else
    19             return max(getDepth(p->left, deep+1), getDepth(p->right, deep+1));
    20     }
    21 };
  • 相关阅读:
    「BJOI2018」治疗之雨
    「NOIP2016」换教室
    「HNOI2015」亚瑟王
    2019/9/15 四校联训
    【AtCoder】 ARC 097
    【AtCoder】 ARC 098
    【AtCoder】 ARC 099
    【AtCoder】 ARC 100
    React:JS中的this和箭头函数
    React:styled-components
  • 原文地址:https://www.cnblogs.com/yocichen/p/10907210.html
Copyright © 2011-2022 走看看