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.

     https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/

    思路:递归实现,取左右节点中深度小的+1。

      注意:如果左右子树其中一个为null,则应以不为null的子树深度为准,而不是以null的深度0为准。

    public class Solution {
    
        public int minDepth(TreeNode root) {
            if (root == null)
                return 0;
            if (root.left == null)
                return minDepth(root.right) + 1;
            if (root.right == null)
                return minDepth(root.left) + 1;
            else
    
            {
                int minLeft = minDepth(root.left);
                int minRight = minDepth(root.right);
                return (minLeft < minRight ? minLeft : minRight) + 1;
            }
        }
    
        public static void main(String[] args) {
            TreeNode root = new TreeNode(10);
            root.left = new TreeNode(5);
            root.right = new TreeNode(5);
            root.right.left = new TreeNode(9);
    
            System.out.println(new Solution().minDepth(root));
        }
    }
    View Code

    第二遍记录:注意各种终止情况的讨论。

    public class Solution {
    
        public int minDepth(TreeNode root) {
            if(root==null)
                return 0;
            else 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 Math.min(minDepth(root.left),minDepth(root.right)) + 1;
        }
    
    }

    第三遍记录:

    思路完全参考第二遍,写之前画图分析各种情况。

  • 相关阅读:
    SQL多表组合查询
    软件测试基础知识点
    Jenkins可持续集成Python自动化脚本
    自动化总结(三) Unittest的应用2
    unittest单元测试2(转载)
    unittest单元测试(转载)
    自动化总结(二) Unittest的应用
    自动化测试小结(一)
    初识ES数据库(转载)
    功能测试小结(三)
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821430.html
Copyright © 2011-2022 走看看