LeetCode之二叉树最小深度(简单 二叉树)

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

一层一层遍历,每遍历一层,高度+1,知道遇到叶节点,返回高度。

public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int depth = 0;
        while(!q.isEmpty()){
            int size = q.size();
            depth ++;
            for (int i = 0; i < size; i++) {
                TreeNode t = q.poll();
                if(t.left==null&&t.right==null){
                    return depth;
                }
                if(t.left!=null){
                    q.offer(t.left);
                }
                if(t.right!=null){
                    q.offer(t.right);
                }
            }
        }
        return depth;
    }

我一般写非递归之前总会想一想递归算法,但是总是想不完整,我发现这些大神总是能想出递归,只要写几行代码就结束了,气啊,最气的是自己写非递归几十行,运行时间还没人家几行的快,百思不得其解,推测大概是测试数据二叉树的深度不高导致递归的次数不多代码少,自然节约时间。气气气,大神代码走起

public int minDepth(TreeNode root) {
          if (root==null) return 0;
        if (root.left==null &&root.right==null)
            return 1;
        else if (root.left!=null &&root.right !=null)
            return (Math.min (minDepth (root.left), minDepth(root.right)) +1);
        else if (root.left==null)
            return minDepth (root.right)+1;
        else 
            return minDepth (root.left) +1;
    }

基本啥都能给你弄成递归,厉害厉害。

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83575843