- 描述
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
- 思路
首先,肯定需要一种遍历算法来找到所有的元素,而二叉树的遍历一般都会想到这样几种遍历:前、中、后序遍历。而从题目给出的例子来看,显然更符合前序遍历的算法。当然,这到题目最重要的还是判断目前的节点是处于第几层,可以这样想,用一个变量保存当前的层数,当遍历到下一层的时候,该变量自加,结束一层的遍历时,该变量自减,这样就可以判断当前的层数了。综上,可以采用前序遍历的算法作为基础,写出符合题目的算法。下面给出代码。 - 代码(c#)
public IList<IList<int>> LevelOrder(TreeNode root)
{
IList<IList<int>> result = new List<IList<int>>();
int index = 0;//保存当前的层数
LevelOrder(root, result, ref index);
return result;
}
public void LevelOrder(TreeNode root, IList<IList<int>> result,ref int index)
{
if (root == null)
{
index--;
return;
}
if (result.Count <= index)
{
result.Add(new List<int>());//该层还没有元素被保存
}
result[index].Add(root.val);
index++;//将要进入下一层,索引自加
LevelOrder(root.left, result,ref index);
index++;
LevelOrder(root.right, result, ref index);
index--;//已经结束了一层,索引自减
}
- 总结
在拿到一个算法题的时候,可以考虑一些基础的算法,在这些基础算法上面进行改良,以写出符合题目的算法。
- 相关链接
LeetCode原题:https://leetcode.com/problems/binary-tree-level-order-traversal/description/