LeetCode 102. Binary Tree Level Order Traversal 题解

题目链接:https://leetcode.com/problems/binary-tree-level-order-traversal/?tab=Description

题目要求:按层遍历二叉树,并要把每一层的元素放在一个链表中。

思路:如果不要求用嵌套链表的形式存储元素,而只是按层次把元素输出,那可以直接使用队列实现,还比较简单。但是根据本题的要求,我们不得不记录下每一层的起始位置。我的做法如下:在每一层元素结束后,向队列中添加一个”栅栏“作为分割符。

举例来说:对于输入3,9,20,null, null, 15, 7

队列中应该保存的是3 | 9,20 | 15,7  (注:因为不时有出队列操作,所以这个序列并不会真的存在于某一刻的队列中,我只是为了表示出栅栏的标记和划分作用)


Java如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
    	List<List<Integer>> result = new LinkedList<List<Integer>>() ;
        if(root == null){
        	return result;
        }
        // 栅栏节点
        TreeNode fence = new TreeNode(Integer.MIN_VALUE);
    	Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        nodeQueue.add(root);
        nodeQueue.add(fence); 
        TreeNode current;	
        List<Integer> list = new LinkedList<Integer>();
        while(!nodeQueue.isEmpty()){
        	current = nodeQueue.peek();
        	if(current != null ){
        		if(current.val == Integer.MIN_VALUE){
        			// 表示上一层的节点已经处理完毕,将上一层节点数据list加入到result列表中
        			result.add(list);
        			// 当前栅栏出队列
        			nodeQueue.remove();
        			// 如果队列中还有待处理的元素
        			if(!nodeQueue.isEmpty()){
        				// 在目前队列最后面添加新的栅栏
            				nodeQueue.add(fence);
            				// 遇到栅栏表示下一层的节点即将开始处理,重新new一个列表用于放下一层的数据
            				list = new LinkedList<Integer>();
        			}
        		} else {
            		list.add(current.val);
            		// 将current节点的左右节点加入队列,并将current从队列中删除
            		if(current.left != null){
            			nodeQueue.add(current.left);
            		}
            		if(current.right != null){
            			nodeQueue.add(current.right);
            		}
            		nodeQueue.remove();
        		}
        	} else {
        		nodeQueue.remove();
        	}
        }
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值