力扣0114——二叉树展开为链表

[二叉树展开为链表]

难度:中等

题目描述

给你二叉树的根结点 root ,请你将它展开为一个单链表:

  • 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null
  • 展开后的单链表应该与二叉树 先序遍历 顺序相同。

示例1

输入: root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]

示例2

输入: root = []
输出:[]

示例3

输入: root = [0]
输出:[0]

题解

因为和先序遍历相同,所以可以想到利用先序遍历将所有的结点存储到列表中,之后便可以依次添加右子结点

想法代码

using System;
using System.Collections.Generic;

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution
{
    public static void Main(string[] args)
    {
        TreeNode root = new TreeNode
        {
            val = 1,
            left = new TreeNode
            {
                val = 2,
                left = new TreeNode(3),
                right = new TreeNode(4)
            },
            right = new TreeNode
            {
                val = 5,
                right = new TreeNode(6)
            }
        };
        Solution solution = new Solution();
        solution.Flatten(root);
        solution.OnlyReadRightTree(root);
    }

    public IList<TreeNode> treeList = new List<TreeNode>();

    public void Flatten(TreeNode root)
    {
        Travel(root);
        int size = treeList.Count;
        for (int i = 0; i < size; i++)
        {
            TreeNode tree = treeList[i];
            tree.left = null;
            tree.right = i == size - 1 ? null : treeList[i + 1];
        }
    }

    public void Travel(TreeNode root)
    {
        if (root == null)
        {
            return;
        }

        treeList.Add(root);
        Travel(root.left);
        Travel(root.right);
    }

    public void OnlyReadRightTree(TreeNode root)
    {
        if (root == null)
        {
            return;
        }

        OnlyReadRightTree(root.right);
        Console.Write(root.val);
    }
}
return;
        }

        OnlyReadRightTree(root.right);
        Console.Write(root.val);
    }
}

你可能感兴趣的:(算法进修,leetcode,链表,算法)