zoukankan      html  css  js  c++  java
  • leetcode 111二叉树的最小深度

     

    使用深度优先搜索:时间复杂度O(n),空间复杂度O(logn)

    /**
     * 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==NULL) return 0;
            //当左右子树有一个为空时,深度按不为空的算;
            if(root->left==NULL) return 1+minDepth(root->right);
            if(root->right==NULL) return 1+minDepth(root->left);
            //当左右子树都不为空时,深度按照小的算;
            return 1+min(minDepth(root->right),minDepth(root->left));
        }
    };

    精简版:

    /**
     * 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==NULL) return 0;
            int leftDepth=minDepth(root->left);
            int rightDepth=minDepth(root->right);
            return (leftDepth==0 || rightDepth==0)? leftDepth+rightDepth+1:1+min(leftDepth,rightDepth);
        }
    };
  • 相关阅读:
    [PHP] thinkphp5 单入口多个模块绑定和路由开关
    [高并发]幂等性、最终一致性
    [高并发]Beanstalkd消息中间件使用
    [高并发]Redis 集群搭建步骤
    [PHP] laravel5.5 搭建流程
    [PHP] 破Laravel白屏问题
    talk 64
    linux
    yum
    linux修改时区
  • 原文地址:https://www.cnblogs.com/joelwang/p/10692515.html
Copyright © 2011-2022 走看看