广度优先搜索实例

本文通过一系列与广度优先搜索(BFS)相关的二叉树问题,如对称树检查、层次遍历、锯齿形层次遍历、最小树深度和单词阶梯,深入探讨BFS在解决树结构问题中的实践和技巧。通过实例代码展示如何递归和迭代地解决这些问题,强调在实际应用中BFS算法的灵活性。
摘要由CSDN通过智能技术生成

我们在前面的文章《图的广度优先搜索》中介绍了图的广度优先搜索算法,现在继续看一下相关的题目,以加深理解运用。

说明:下面题目中涉及到的tree的结构如下:

/* 
* public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }*/


1.Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

这道题比较容易,遍历每一层,判断每一层是否对称即可。不过需要注意一点,我们在写BFS算法的时候,很多时候并不是严格的遍历完一行再遍历另一行,而是同时进行的。也就是说队列里面可能既有本层的节点,也有下一层的节点。

代码如下:

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.addLast(root);
        ArrayList<TreeNode> r = new ArrayList<TreeNode>();
        TreeNode tmp = null;
        int len = 0;
        while(true){
            while(queue.size()>0){
                tmp = queue.removeFirst();
                r.add(tmp);
            }
            len = r.size();
            for(int i = 0;i < len/2;i++){
                if(r.get(i) == null && r.get(len-i-1) == null) continue;
                else if(r.get(i) == null || r.get(len-i-1) == null) return false;
                if(r.get(i).val != r.get(len-i-1).val) return false;
            }
            for(int i = 0;i < len; i++){
                tmp = r.get(i);
                if(tmp==null) continue;
                queue.addLast(tmp.left);
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值