二叉树

论坛 期权论坛 脚本     
已经匿名di用户   2022-4-26 15:52   2457   0

上学学数据结构的时候,最怕的就是树 。毕业写了一年多的程序了,或许是前面的后遗症至今对树还很怕!
昨天面试的时候直接考得就是树,当时有些紧张,大脑出现断路,最终在面试官的帮助下,磕磕绊绊的写了个求深度的函数。
今天闲暇时,想了想自己写了棵树。不是很全面。
主要包括了求树的深度,树的的最大节点值,最小节点值。树上添加新的节点。现在把代码贴出来,仅供参考。

class Program
{
static void Main(string[] args)
{
Tree t1
= new Tree(1);
Tree t2
= new Tree(2);
Tree t3
= new Tree(3);
Tree t4
= new Tree(4);
Tree t5
= new Tree(5);

Tree.AppendChild(t3, t1);
Tree.AppendChild(t3, t2);
Tree.AppendChild(t3, t4);
Tree.AppendChild(t3, t5);

Console.WriteLine( t3.MaxValue);
}

}


public class Tree
{
private Tree leftChild;
private Tree rightChild;
private int treeValue;

public Tree(int value)
{
treeValue
= value;
}


public int TreeValue
{
get
{
return treeValue;
}

set
{
treeValue
= value;
}

}


public static void AppendChild(Tree old, Tree newer)
{
if (newer.TreeValue >= old.TreeValue)
{
if (old.RightChild == null)
{
old.rightChild
= newer;
}

else
{
AppendChild(old.RightChild, newer);
}

}

else
{
if (old.leftChild == null)
{
old.leftChild
= newer;
}

else
{
AppendChild(old.leftChild, newer);
}

}

}


public int MinValue
{
get
{
return GetMinNode(this).TreeValue;
}

}


public int MaxValue
{
get
{
return GetMaxNode(this).TreeValue;
}

}


private Tree GetMinNode( Tree tree)
{
if (tree.leftChild == null)
{
return tree;
}

else
{
return GetMinNode(tree.leftChild);
}

}

private Tree GetMaxNode(Tree tree)
{
if (tree.rightChild == null)
{
return tree;
}

else
{
return GetMaxNode(tree.rightChild);
}

}


public Tree LeftChild
{
get
{
return leftChild;
}

}


public Tree RightChild
{
get
{
return rightChild;
}

}


public int Deep
{
get
{
return GetDeep();
}

}


private int GetDeep()
{

if (rightChild == null && leftChild == null)
{
return 0;
}

int rightDeep = 0;
int leftDeep = 0;
if (rightChild != null)
{
rightDeep
= rightChild.Deep;
}

if (leftChild != null)
{
leftDeep
= leftChild.Deep;
}

return Math.Max(leftDeep, rightDeep) + 1;
}


public static int GetDeep(Tree tree)
{
if (tree == null)
{
return -1;
}

else
{

if (tree.rightChild == null && tree.leftChild == null)
{
return 0;
}

int rightDeep = 0;
int leftDeep = 0;
if (tree.rightChild != null)
{
rightDeep
= tree.rightChild.Deep;
}

if (tree.leftChild != null)
{
leftDeep
= tree.leftChild.Deep;
}

return Math.Max(leftDeep, rightDeep) + 1;
}

}

}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP