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
  • 相关阅读:
    [NOIP2011] 玛雅游戏
    [bzoj4025] 二分图
    [10.2模拟] tree
    [10.3模拟] color
    [10.2模拟] teach
    [10.2模拟] plan
    [10.2模拟] book
    [bzoj4999] This Problem Is Too Simple!
    [9.28模拟] good
    [bzoj3884] 上帝与集合的正确用法
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3590421.html
Copyright © 2011-2022 走看看