LeeCode102二叉树的层序遍历(Java)(层序遍历)

题目链接:LeeCode102二叉树的层序遍历
题目描述:在这里插入图片描述
先说说层序遍历,利用队列的性质,将树的左右节点依次放队列中,按题目中给的树就是先将三入队,进入循环,3出队,将3的左右入队,再取队首,依次执行,代码实现就是:

public static List<Integer> levelOrder(TreeNode root) {
    
    
        Queue<TreeNode> queue=new LinkedList<>();
        List<List<Integer>> lists=new ArrayList<>();
        List<Integer> list=new ArrayList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
    
    
            TreeNode poll = queue.poll();
            list.add(poll.val);
            if(poll.left!=null) queue.offer(poll.left);
            if(poll.right!=null) queue.offer(poll.right);
        }
        return list;
    }

再看这个题,就是需要判断第几层有几个元素,然后每层存到一个list里面,所以用一个数组存下来即可。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public static List<List<Integer>> levelOrder(TreeNode root) {
    
    
        Queue<TreeNode> queue=new LinkedList<>();
        List<List<Integer>> lists=new ArrayList<>();
        List<Integer> list=new ArrayList<>();
        if(root==null) return new ArrayList<>();
        int[] cnt=new int[1005];
        queue.offer(root);
        cnt[0]=1;
        int index=0;
        while (!queue.isEmpty()) {
    
    
            TreeNode poll = queue.poll();
            list.add(poll.val);
            if(poll.left!=null){
    
    
            	//当前层节点有一个左节点所以下一层技术加一
                cnt[index+1]++;
                queue.offer(poll.left);
            }
            if(poll.right!=null){
    
    
            	//同理加一
                cnt[index+1]++;
                queue.offer(poll.right);
            }
            //每次遍历完一个节点就令当前层节点记录数减1
            cnt[index]--;
            //如果这层遍历完了就到下一层并记录当前层list,清空list
            if(cnt[index]==0){
    
    
                index++;
                lists.add(new ArrayList<>(list));
                list.clear();
            }
        }
        return lists;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/112969629
今日推荐