zoukankan      html  css  js  c++  java
  • Minimum Depth of Binary Tree ——LeetCode

    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://leetcode.com/problems/minimum-depth-of-binary-tree/

    题意就是给定一个二叉树,找出从根节点到叶子节点最低的高度,直接写了个递归,算出所有叶子节点的高度,取最小值。

    另外一种很显然就用层次遍历(BFS), 就是按层次遍历这棵树,发现当前节点是叶子节点,就直接返回这个节点的高度。这里有个问题就是怎么记录当前的高度呢?我是这么做的:设置三个变量,upRow,downRow,height,分别代表队列中上一行节点数,下一行节点数,高度,当队列中上一行节点数为0,那么高度+1,把下一行的节点数量(downRow)赋给上一行(upRow),循环不变式是队列非空(!queue.isEmpty())。

    Talk is cheap。

    import java.util.LinkedList;
    import java.util.List;
    
    /**
     * Created with IntelliJ IDEA.
     * User: Blank
     * Date: 2015/3/21
     */
    public class MinimumDepthofBinaryTree {
    
        public int minDepth(TreeNode root) {
            int left = Integer.MAX_VALUE, right = Integer.MAX_VALUE;
            if (root == null)
                return 0;
            if (root.right == null && root.left == null)
                return 1;
            if (root.left != null)
                left = minDepth(root.left) + 1;
            if (root.right != null)
                right = minDepth(root.right) + 1;
            return Math.min(left, right);
        }
    
        public int minDepth2(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int upRow = 1, downRow = 0, height = 0;
            List<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.get(0);
                queue.remove(0);
                if (node.left == null && node.right == null)
                    return height + 1;
                if (node.left != null) {
                    queue.add(node.left);
                    downRow++;
                }
                if (node.right != null) {
                    queue.add(node.right);
                    downRow++;
                }
                upRow--;
                if (upRow == 0) {
                    height++;
                    upRow = downRow;
                    downRow = 0;
                }
            }
            return height;
        }
    }
  • 相关阅读:
    P1041 传染病控制(dfs)
    洛谷P1040 加分二叉树(树形dp)
    微信支付移动开发
    UVA
    Android开源框架ViewPageIndicator和ViewPager实现Tab导航
    Android Application Digital Signatures
    android:怎样在TextView实现图文混排
    python无私有成员变量
    unity3D游戏开发实战原创视频讲座系列11之相扑游戏开发并公布到WinWP8
    MFC:Win32-Dll及MFC-Dll编写调用
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4356596.html
Copyright © 2011-2022 走看看