/// <summary>
/// 求一棵二叉树中相距最远的两个节点之间的最大距离
/// </summary>
public class BinaryTreeMaxLength
{
public static void Do()
{
//创建二叉树
Node head = CreateTree();
//显示
Console.WriteLine(LevelOrderTraversal(head));
int maxDistance = 0;
GetMaxLength(head, ref maxDistance);
}
public static Data GetMaxLength(Node cur, ref int maxDistance)
{
if (cur == null)
return new Data() { LeftMaxDistance=-1,RightMaxDistance=-1};
//遍历到最左子节点
Data leftData = GetMaxLength(cur.Left, ref maxDistance);
//遍历到最右子节点
Data rightData = GetMaxLength(cur.Right, ref maxDistance);
//获得距离
Data returnData = new Data();
returnData.LeftMaxDistance = Math.Max(leftData.LeftMaxDistance, leftData.RightMaxDistance) + 1;
returnData.RightMaxDistance = Math.Max(rightData.LeftMaxDistance, rightData.RightMaxDistance) + 1;
//设置最大距离
int maxDistanceTmp = returnData.LeftMaxDistance + returnData.RightMaxDistance;
maxDistance = maxDistanceTmp > maxDistance ? maxDistanceTmp : maxDistance;
return returnData;
}
public static Node CreateTree()
{
Node[] array = new Node[14];
for (int i = 0; i < 14; i++)
{
Node tmp = new Node() { Num = i };
array[i] = tmp;
}
Link(array, 1, 2, 3);
Link(array, 2, 4, 5);
Link(array, 3, 6, 7);
Link(array, 5, 8, 9);
Link(array, 6, 10, 11);
Link(array, 8, 12, -1);
Link(array, 10, 13, -1);
return array[1];
}
public static void Link(Node[] array, int parent, int left, int right)
{
if (parent >= 0 && parent < array.Length)
{
if (left >= 0 && left < array.Length)
{
array[parent].Left = array[left];
}
if (right >= 0 && right < array.Length)
{
array[parent].Right = array[right];
}
}
}
public static string LevelOrderTraversal(Node cur)
{
string output = string.Empty;
if (cur == null)
return output;
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(cur);
Node tmp = null;
while (queue.Count != 0)
{
tmp = queue.Dequeue();
output += tmp.Num + ",";
if (tmp.Left != null)
{
queue.Enqueue(tmp.Left);
}
if (tmp.Right != null)
{
queue.Enqueue(tmp.Right);
}
}
return output;
}
public class Node
{
public int Num;
public Node Left;
public Node Right;
}
public class Data
{
public int LeftMaxDistance;
public int RightMaxDistance;
}
}