Leetcode之二叉树的层序遍历

问题描述

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:
二叉树:[3,9,20,null,null,15,7],

返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]

问题解法

先构建广度优先搜索,再设置一个指针标志这一层有多少个节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   public  List<List<Integer>> levelOrder(TreeNode root) {
		 if(root==null)
			 return new ArrayList<List<Integer>>();
	        Queue<TreeNode> q=new LinkedList<TreeNode>();
	        int end=1;
	        TreeNode p=root;
	        q.add(p);
	        ArrayList<List<Integer>> list1=new ArrayList<List<Integer>>();
	        ArrayList<Integer> list=new ArrayList<Integer>();
	        while(!q.isEmpty()) {
	        	p=q.poll();
	        	if(p.left!=null)
	        		q.add(p.left);
	        	if(p.right!=null)
	        		q.add(p.right);
	        	list.add(p.val);
	        	end--;
	        	if(end==0) {
	        		end=q.size();
	        		list1.add(list);
	        		list=new ArrayList<Integer>() ;
	        	}
	        }
	        return list1;
	    }
}

运行结果

原文地址:https://www.cnblogs.com/code-fun/p/13767784.html