zoukankan      html  css  js  c++  java
  • 【leetcode】Minimum Depth of Binary Tree (easy)

    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.

    简单题,不过注意叶子结点是两个子树都是NULL的指针。只有一个子树NULL的不是。

     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;
            }
            else if(root->left == NULL)
            {
                return minDepth(root->right) + 1;
            }
            else if(root->right == NULL)
            {
                return minDepth(root->left) + 1;
            }
            else 
            {
                return min(minDepth(root->left), minDepth(root->right)) + 1;
            }
        }
    };
  • 相关阅读:
    vijos 1379 字符串的展开
    BZOJ 4597 随机序列
    BZOJ 2303 方格染色
    BZOJ 2654 tree
    BZOJ 4198 荷马史诗
    BZOJ 1555 KD之死
    不重复数字
    Rails
    Train Problem I
    Key Set HDU
  • 原文地址:https://www.cnblogs.com/dplearning/p/4116406.html
Copyright © 2011-2022 走看看