using System;
using System.Collections.Generic;
/*
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode (int x)
{
val = x;
}
}
*/
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型二维数组
*/
List<List<int>> res = new List<List<int>>();
public List<List<int>> levelOrder (TreeNode root) {
// write code here
if(root == null) return res;
BFS(root, 0);
return res;
}
void BFS(TreeNode root, int level)
{
List<int> list;
if(res.Count == level)
{
list = new List<int>();
res.Add(list);
}
//引用赋值
list = res[level];
list.Add(root.val);
if(root.left != null)
{
BFS(root.left, level + 1);
}
if(root.right != null)
{
BFS(root.right, level + 1);
}
}
}
BM26 求二叉树的层序遍历
于 2023-08-29 08:53:22 首次发布