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

    Maximum Depth of Binary Tree

    可以这样写

    1 int maxDepth(TreeNode *root) {
    2         if(!root)
    3             return 0;
    4         else
    5             return 1+max(maxDepth(root->left),maxDepth(root->right));
    6     }

    Minimum Depth of Binary Tree

    如果仿照上面

    1 int minDepth(TreeNode *root) {
    2         if(!root)
    3             return 0;
    4         else
    5             return 1+min(minDepth(root->left),minDepth(root->right));
    6     }

    Status: Wrong Answer

    Input: {1,2}
    Output: 1
    Expected: 2

    根据这个错误的提示,需要加上两个判断

    1 if(!(root->right)&&root->left)
    2             return 1+minDepth(root->left);
    3         else if(!(root->left)&&root->right)
    4             return 1+minDepth(root->right);

    AC 完整代码:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int minDepth(TreeNode *root) {
    13         if(!root)
    14             return 0;
    15         if(!(root->right)&&root->left)
    16             return 1+minDepth(root->left);
    17         else if(!(root->left)&&root->right)
    18             return 1+minDepth(root->right);
    19         else
    20             return 1+min(minDepth(root->left),minDepth(root->right));
    21     }
    22 };
    View Code
  • 相关阅读:
    Elasticsearch源码加载到eclipse调试
    Elasticsearch基础教程
    关于JAVA EE项目在WEB-INF目录下的jsp页面如何访问WebRoot中的CSS和JS文件
    访问WEB-INF下的JSP (转载)
    SqlServer的代理问题
    SqlServer进行程序跟踪
    git简单的修改
    Linux部署项目
    网址仓库
    Linux基础
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3590421.html
Copyright © 2011-2022 走看看