首页 > 其他 > 详细

[LeetCode]111 Minimum Depth of Binary Tree

时间:2015-01-06 15:45:16      阅读:162      评论:0      收藏:0      [点我收藏+]

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

http://blog.csdn.net/linhuanmars/article/details/19660209

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) 
    {
        if (root == null)
            return 0;

        // Solution A
        // return minDepth_DFS(root, 1);
        
        // Solution B
        return minDepth_BFS(root);
    }
    
    //////////////////////////
    // Solution A: DFS
    //
    private int minDepth_DFS(TreeNode node, int v)
    {
        if (node.left == null && node.right == null)
            return v;   // leaf
            
        if (node.left == null)
        {
            return minDepth_DFS(node.right, v + 1);
        }
        else if (node.right == null)
        {
            return minDepth_DFS(node.left, v + 1);
        }
        else
        {
            return Math.min(minDepth_DFS(node.left, v + 1), minDepth_DFS(node.right, v + 1));
        }
    }

    //////////////////////////
    // Solution B: BFS
    //
    private int minDepth_BFS(TreeNode root)
    {
        Queue<TreeNode> queue = new LinkedList<>();
        root.val = 1;
        queue.offer(root);
        
        while (!queue.isEmpty())
        {
            TreeNode node = queue.poll();
            
            if (node.left == null && node.right == null)
                return node.val;
            
            if (node.left != null)
            {
                node.left.val = node.val + 1;
                queue.offer(node.left);
            }
            if (node.right != null)
            {
                node.right.val = node.val + 1;
                queue.offer(node.right);
            }
        }
        
        return -1; // Invalid case.
    }
}


[LeetCode]111 Minimum Depth of Binary Tree

原文:http://7371901.blog.51cto.com/7361901/1599712

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!