Lintcode155:非递归求二叉树的最小深度

题目

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.

解题思路

通过层序遍历二叉树的方式,记录层序遍历的层数,在第一次遇到左右节点都为空的点时,即认为到达最短的二叉树路径。返回此时记录的层数。

代码

节点的定义:

public class TreeNode {
	public int val;
	public TreeNode left, right;
 	public TreeNode(int val) {
		this.val = val;
		this.left = this.right = null;
	}
}

层序遍历实现求最小深度:

public class Solution {
    /**
     * @param root: The root of binary tree
     * @return: An integer
     */
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        //用于记录遍历层数
        int min = 0;
        LinkedList<TreeNode> l1 = new LinkedList<TreeNode>();
        LinkedList<TreeNode> l2 = new LinkedList<TreeNode>();
        l1.add(root);
        while(!l1.isEmpty() || !l2.isEmpty()){
            min++;
            if(l2.isEmpty()){
                while(!l1.isEmpty()){
                    TreeNode n = l1.poll();
                    //左右节点都为空,即认为找到了最小深度
                    if(n.left == null && n.right == null){
                        return min;
                    }
                    if(n.left!=null){
                        l2.add(n.left);
                    }
                    if(n.right!=null){
                        l2.add(n.right);
                    }
                }
            }else{
                while(!l2.isEmpty()){
                    TreeNode n = l2.poll();
                    if(n.left == null && n.right == null){
                        return min;
                    }
                    if(n.left!=null){
                        l1.add(n.left);
                    }
                    if(n.right!=null){
                        l1.add(n.right);
                    }
                }
            }
           
        }
        return min;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值