c#

c#二叉树如何转换为双向链表

小樊
84
2024-07-26 02:43:14
栏目: 编程语言

要将二叉树转换为双向链表,可以使用中序遍历来实现。具体步骤如下:

  1. 创建一个类来表示双向链表的节点,包括指向前一个节点和后一个节点的指针。
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;
    }
}
  1. 创建一个类来表示二叉树的节点,包括左子节点和右子节点。
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;
    }
}
  1. 编写一个递归函数来实现中序遍历,并在遍历过程中将二叉树转换为双向链表。
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);
    }
}
  1. 在主函数中调用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;
        }
    }
}

运行上面的代码,即可将二叉树转换为双向链表,并输出双向链表的值。

0
看了该问题的人还看了