Problem: 102. 二叉树的层序遍历
文章目录
- 思路
- 复杂度
- Code
思路
路飞
复杂度
时间复杂度:
添加时间复杂度, 示例:
O
(
n
)
O(n)
O(n)
空间复杂度:
添加空间复杂度, 示例:
O
(
n
)
O(n)
O(n)
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* 服务器托管网 TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* 服务器托管网 this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List> levelOrder(TreeNode root)
{
List> ans = new ArrayList();
LinkedList q = new LinkedList();
if (root == null)
return ans;
q.add(root);
while (!q.isEmpty())
{
int n = q.size();
ArrayList list = new ArrayList(n);
while (n-- > 0)
{
TreeNode node = q.poll();
list.add(node.val);
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
ans.add(list);
}
return ans;
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net