Minimum Depth of Binary Tree——LeetCode(Easy)

来源:互联网 发布:网络语斯什么意思 编辑:程序博客网 时间:2024/05/01 16:10

题目: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.

           意思就是寻找二叉树里面的最小路径


我自己写的代码如下:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int minDepth(TreeNode *root) {                if (root == NULL)        {            return 0;        }                if (root->left == NULL && root->right == NULL)        {            return 1;        }                int minLeft = minDepth(root->left);        int minRight = minDepth(root->right);                if (minLeft == 0)            return minRight+1;        if (minRight == 0)            return minLeft+1;                return minLeft < minRight ? minLeft+1 : minRight+1;     }};

觉得自己写的有点啰嗦,判定那一段写的不够精炼,在网上找了别人的代码比较一下:

class Solution {  public:      int minDepth(TreeNode *root) {          // Start typing your C/C++ solution below          // DO NOT write int main() function          if(root)          {              if(root->left == NULL && root->right == NULL)                  return 1;              else if(root->left == NULL)                  return minDepth(root->right) + 1;              else if(root->right == NULL)                  return minDepth(root->left) + 1;              return min(minDepth(root->left), minDepth(root->right)) + 1;          }          return 0;             }  };  

看来代码这东西还是得多敲!

0 0