LintCode 69---二叉树的层次遍历

 2023-09-11 阅读 20 评论 0

摘要:/*** Definition of TreeNode:* public class TreeNode {* public int val;* public TreeNode left, right;* public TreeNode(int val) {* this.val = val;* this.left = this.right = null;* }* }*/public class Solution {/*** 给出一棵二叉树,返回其节
/*** Definition of TreeNode:* public class TreeNode {*     public int val;*     public TreeNode left, right;*     public TreeNode(int val) {*         this.val = val;*         this.left = this.right = null;*     }* }*/public class Solution {/*** 给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右)* @param root: A Tree* @return: Level order a list of lists of integer*/public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result = new ArrayList<>();//判断根节点是否为空if (root == null){return result;}//定义一个队列,并添加根节点Queue<TreeNode> queue = new LinkedList<>();queue.add(root);TreeNode node = null;while (!queue.isEmpty()){int size = queue.size();List<Integer> level = new ArrayList<>();for (int i = 0; i < size; i++) {node = queue.poll();level.add(node.val);if(node.left != null){queue.add(node.left);}if(node.right != null){queue.add(node.right);}}result.add(level);}return result;}
}

 

转载于:https://www.cnblogs.com/cnmoti/p/10828422.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/43856.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息