要将二叉树转换为双向链表,可以使用中序遍历来实现。具体步骤如下:
- 创建一个类来表示双向链表的节点,包括指向前一个节点和后一个节点的指针。
public class Node
{
public int val;
public Node prev;
public Node next;
public Node(int val)
{
this.val = val;
this.prev = null;
this.next = null;
}
}
- 创建一个类来表示二叉树的节点,包括左子节点和右子节点。
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val)
{
this.val = val;
this.left = null;
this.right = null;
}
}
- 编写一个递归函数来实现中序遍历,并在遍历过程中将二叉树转换为双向链表。
public class Solution { private Node prev; public Node Convert(TreeNode root) { if (root == null) return null; Node dummy = new Node(-1); prev = dummy; InOrder(root); Node head = dummy.next; head.prev = null; return head; } private void InOrder(TreeNode node) { if (node == null) return; InOrder(node.left); Node current = new Node(node.val); prev.next = current; current.prev = prev; prev = current; InOrder(node.right); } }
- 在主函数中调用
Convert
方法,将二叉树转换为双向链表。
class Program
{
static void Main(string[] args)
{
TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
Solution solution = new Solution();
Node head = solution.Convert(root);
// 遍历双向链表
Node currentNode = head;
while (currentNode != null)
{
Console.Write(currentNode.val + " ");
currentNode = currentNode.next;
}
}
}
运行上面的代码,即可将二叉树转换为双向链表,并输出双向链表的值。