题目1:二叉树的镜像
思路:递归
8 8
6 10 转换成 10 6
5 7 9 11 11 9 7 5
static void SwapNode(Node node) { if (node == null) { return; } Node temp = node.Left; node.Left = node.Right; node.Right = temp; SwapNode(node.Left); SwapNode(node.Right); }
题目2:从上往下打印二叉树
思路:利用队列(广度优先)
static void PrintFromTopToBottom(Node node) { if (node == null) { return; } Queue<Node> queue = new Queue<Node>(); queue.Enqueue(node); while (queue.Count > 0) { Node current = queue.Dequeue(); Console.WriteLine(current.Value); if (current.Left != null) { queue.Enqueue(current.Left); } if (current.Right != null) { queue.Enqueue(current.Right); } } }
时间: 2024-10-31 04:17:40