题目描述:
ZigZag方式遍历二叉树,即:根->左子->右子->右子的左子->右子的右子->XXX
实现:
public class Solution {
public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
IList<IList<int>> result = new List<IList<int>>();
if(root == null)
{
return result;
}
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
bool isOrder = true;
int size = 1;
while(q.Count > 0)
{
List<int> tmp = new List<int>();
for(int i = 0; i < size; ++i) {
TreeNode n = q.Dequeue();
if(isOrder)
{
tmp.Add(n.val);
}
else
{
tmp.Insert(0, n.val);
}
if(n.left != null)
{
q.Enqueue(n.left);
}
if(n.right != null)
{
q.Enqueue(n.right);
}
}
result.Add(tmp);
size = q.Count;
isOrder = isOrder ? false : true;
}
return result;
}
}
本文介绍了一种特殊的二叉树遍历方法——ZigZag遍历,并提供了一个具体的C#实现示例。该遍历方法从根节点开始,依次遍历左子节点、右子节点,然后从右子节点的左子节点开始,再遍历右子节点,以此类推。文章通过使用队列和布尔标志来区分每一层的遍历方向。
299

被折叠的 条评论
为什么被折叠?



