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);
        }
    };
  • 相关阅读:
    NAVICAT 拒绝链接的问题
    .net垃圾回收-原理浅析
    C#中标准Dispose模式的实现
    Windbg调试托管代码
    C#泛型基础
    .Net垃圾回收和大对象处理
    C++ 小知识点
    C++之虚函数表
    C++之指针与引用,函数和数组
    C++之const关键字
  • 原文地址:https://www.cnblogs.com/joelwang/p/10692515.html
Copyright © 2011-2022 走看看