• 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
  • 相关阅读:
    [转]java常量池理解总结
    设计数据库时使用外键吗
    ajax 下载文件
    CentOS6.4配置163的yum源
    Xms Xmx PermSize MaxPermSize 区别
    [转]基于java的程序OutOfMemory问题的解决及Xms/Xmx/Xss的解释和应用
    Java Web Services面试
    java 单例模式
    Spring和MyBatis整合
    Spring核心概念
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3590421.html
Copyright © 2020-2023  润新知