• LeetCode【111. 二叉树的最小深度】


    最小深度,看起来很简单,就是左右节点的深度最小值

    定义一个函数,计算其深度

    class Solution {
        public int minDepth(TreeNode root) {
            if(root == null)
            {
                return 0;
            }
            else if(root.left == null && root.right ==null)
            {
                return 1;
            }
            else
            {
                int left = Depth(root.left);
                int right = Depth(root.right);
                if(left > right)
                {
                return left;
                }
                else
                {
                    return right;
                }
            }
        }
        public int Depth(TreeNode root)
        {
            if(root == null)
            {
                return 0;
            }
            else
            {
                int left = Depth(root.left);
                int right = Depth(root.right);
                if(left<right)
                {
                    return left+1;
                }
                else
                {
                    return right+1;
                }
            }
        }
    }

    有错误在于,[1,2],只有一个节点,然后,该代码就会直接输出1,因为另一个没有节点,那么就直接是1

    但实际上,应该是到叶子节点,不应该有叶子节点,而仍然只算根节点。

    而且定义的函数其实和本函数类似,那么就可以直接迭代本函数,不需要另外定义。

    class Solution {
        public int minDepth(TreeNode root) {
            if(root == null)
            {
                return 0;
            }
            else if(root.left == null && root.right ==null)
            {
                return 1;
            }
            else
            {
                int left = minDepth(root.left);
                int right = minDepth(root.right);
                if(left == 0 && right > 0)
                {
                    return right+1;
                }
                else if(right == 0 && left > 0)
                {
                    return left+1;
                }
                else if(left > right)
                {
                    return right+1;
                }
                else
                {
                    return left+1;
                }
            }
        }
    }

    后面增加了上述情况,不会只算根节点。

  • 相关阅读:
    linux如何用yum进行部署xampp环境
    jmeter关联案例的几种方法
    jmeter中元件
    CentOS7在VMware下设置成桥接模式
    CentOS7使用vsftpd搭建ftp
    虚拟机WMware15和CnetOS7安装
    MySql忘记密码的解决方案
    Windows下MySql8解压版的安装与完全卸载
    Idea设置统一为utf-8编码格式
    Idea常用快捷键
  • 原文地址:https://www.cnblogs.com/wzwi/p/10768417.html
Copyright © 2020-2023  润新知