给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
提示:
0 <= 二叉树的结点数 <= 1500
解题
使用队列和普通的层次遍历不同,这个题目需要存储结果
import java.util.*; class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution { public static void main(String[] args) { Solution solution = new Solution(); TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(4); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); root.left.left = new TreeNode(5); root.left.right = new TreeNode(3); ArrayList> res = solution.levelOrder(root); System.out.println(res.toString()); } public ArrayList> levelOrder(TreeNode root) { // write code here ArrayList> list = new ArrayList<>(); if (root == null) { return list; } Queuequeue = new linkedList<>(); queue.add(root); while (!queue.isEmpty()) { int size = queue.size(); ArrayList subList = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } subList.add(node.val); } list.add(subList); } return list; } }
普通的层次遍历比较的简单
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution { private Listlist = new ArrayList<>(); public static void main(String[] args) { Solution solution = new Solution(); TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(4); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); root.left.left = new TreeNode(5); root.left.right = new TreeNode(3); List list = solution.doSolution(root); System.out.println(list.toString()); } private List doSolution(TreeNode root) { if (root == null) { return new ArrayList<>(); } Queue queue = new linkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); list.add(node.val); if (node.left != null) { queue.add(node.right); } if (node.right != null) { queue.add(node.left); } } return list; } }
输出的是这样的格式
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)