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;
    }
}

 

posted @ 2015-03-22 00:18  丶Blank  阅读(195)  评论(0编辑  收藏  举报