首页 > 其他 > 详细

LeetCode 111: Minimum Depth of Binary Tree

时间:2020-05-08 12:53:09      阅读:42      评论:0      收藏:0      [点我收藏+]
/**
 * 111. Minimum Depth of Binary Tree
 * 1. Time:O(n)  Space:O(h)
 * 2. Time:O(n)  Space:O(h)
 */

// 1. Time:O(n)  Space:O(h)
class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null && root.right==null) return 1;
        int min = Integer.MAX_VALUE;
        if(root.left!=null)
            min = Math.min(minDepth(root.left),min);
        if(root.right!=null)
            min = Math.min(minDepth(root.right),min);
        return min+1;
    }
}

// 2. Time:O(n)  Space:O(h)
class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode last = null;
        int level=0,minLevel=Integer.MAX_VALUE;
        while(root!=null || !stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                level++;
                root = root.left;
            }
            TreeNode tmp = stack.peek();
            if(tmp.right!=null && tmp.right!=last)
                root = tmp.right;
            else{
                if(tmp.left==null && tmp.right==null)
                    minLevel = Math.min(minLevel,level);
                last = stack.pop();
                level--;
            }
        }
        return minLevel;
    }
}

LeetCode 111: Minimum Depth of Binary Tree

原文:https://www.cnblogs.com/AAAmsl/p/12849334.html

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