Link binary tree nodes at the same level

Given modified binary tree node
public class TreeNode<T>
{
    public TreeNode<T> LeftChild;
    public TreeNode<T> RightChild;
    public TreeNode<T> Right;
}
        public static void LinkEachLevel<T>(TreeNode<T> root)
        {
            LinkedList<TreeNode<T>> rightMost = new LinkedList<TreeNode<T>>();
            LinkedListNode<TreeNode<T>> first = new LinkedListNode<TreeNode<T>>(null);
            rightMost.AddFirst(first);
            LinkEachLevel(root, rightMost.First);
        }
 
        public static void LinkEachLevel<T>(TreeNode<T> node, LinkedListNode<TreeNode<T>> rightNode)
        {
            if (rightNode.Value != null)
            {
                node.Right = rightNode.Value;
            }
            rightNode.Value = node;
            if (rightNode.Next == null)
            {
                rightNode.List.AddLast(new LinkedListNode<TreeNode<T>>(null));
            }
            if (node.RightChild != null)
            {
                LinkEachLevel((TreeNode<T>)node.RightChild, rightNode.Next);
            }
            if (node.LeftChild != null)
            {
                LinkEachLevel((TreeNode<T>)node.LeftChild, rightNode.Next);
            }
        }
 
 
Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s