数据结构&算法-线索二叉树

Posted 彩色墨水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构&算法-线索二叉树相关的知识,希望对你有一定的参考价值。

运行结果

在这里插入图片描述

代码

using System;


namespace ThreadedBinaryTree
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadedBinaryTreeC threadedBinaryTreeC = new ThreadedBinaryTreeC();
            string[] strarry = new string[] { "A", "B", "C", "D", "E", "F" };
            ThreadedBinaryTreeC.Node root = threadedBinaryTreeC.CreateBinaryTree(strarry, 0);
            threadedBinaryTreeC.inThreadOrder(root);
            threadedBinaryTreeC.inThreadList(root);
        }
    }

    class ThreadedBinaryTreeC
    {
        Node preNode = null;
        public class Node
        {
            public string data;
            public Node left;
            public Node right;
            public bool leftType;
            public bool rightType;
            public Node(string data)
            {
                this.data = data;
            }
        }

        public Node CreateBinaryTree(string[] array, int index)
        {
            Node node = null;
            if (index < array.Length)
            {
                node = new Node(array[index]);
                node.left = CreateBinaryTree(array, index * 2 + 1);
                node.right = CreateBinaryTree(array, index * 2 + 2);
            }
            return node;
        }

        public void inThreadOrder(Node node)
        {
            while (node == null)
            {
                return;
            }
           
            inThreadOrder(node.left);
            if (node.left == null)
            {
                node.left = preNode;
                node.leftType = true;
            }
            if (preNode != null && preNode.right == null)
            {
                preNode.right = node;
                preNode.rightType = true;
            }

            preNode = node;
          
            inThreadOrder(node.right);
        }

        public void inThreadList(Node node)
        {
            while (node != null && !node.leftType)
            {
                node = node.left;
            }
            while (node != null)
            {
                Console.WriteLine(node.data);
                if (node.rightType)
                {
                    node = node.right;
                }
                else
                {
                    node = node.right;
                    while (node != null && !node.leftType)
                    {
                        node = node.left;
                    }
                }
            }
        }
    }


}

参考
线索二叉树原理及前序、中序线索化(Java版)

以上是关于数据结构&算法-线索二叉树的主要内容,如果未能解决你的问题,请参考以下文章

数据结构与算法__07--前序中序后序线索化二叉树,前序中序后序线索化二叉树遍历(Java语言版本)

数据结构与算法__03--二叉树前序线索化与前序线索化遍历(Java语言版)

算法——建立线索二叉树

数据结构与算法:树 线索化二叉树(中,前,后序)

数据结构与算法:树 线索化二叉树(中,前,后序)

王道数据结构与算法树(八——2)