zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    二叉树的最小深度。

    使用递归求解:

    如果根节点为空,返回0。

    如果左节点为空,递归计算右节点。

    如果右节点为空,递归计算左节点。

    返回1 + 左子树和右子树的最小深度。

    /**
     * Definition for a binary tree node.
     * 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 == nullptr)
                return 0;
            if (root->left == nullptr)
                return 1 + minDepth(root->right);
            if (root->right == nullptr)
                return 1 + minDepth(root->left);
            return 1 + min(minDepth(root->left), minDepth(root->right));
        }
    };
    // 6 ms
  • 相关阅读:
    Time
    算法与结构
    11
    DateUtils
    Ext.container.Container
    Ext.Component
    extjs布局--只看现象
    Ext下的方法
    充血模式与贫血模式
    ext下的组建,mvc,mvvm
  • 原文地址:https://www.cnblogs.com/immjc/p/7682184.html
Copyright © 2011-2022 走看看