二叉树
程序员文章站
2022-06-15 23:43:00
...
二叉树设置:
二叉树创建:
二叉树遍历:(根据访问根节点的时机,分为三种遍历方式)
先序遍历:根左右(访问根节点在最前边)
中序遍历:左根右(访问根节点在中间)
后序遍历:左右根(访问根节点在最后边)
查找特定节点:
查找特定节点的父节点:
C#实现:
建立二叉树:
[DebuggerDisplay("Value={Value}")]
public class Tree
{
public string Value;
public Tree Left;
public Tree Right;
}
public static Tree CreatFakeTree()
{
Tree tree = new Tree() {Value = "A"};
tree.Left = new Tree()
{
Value = "B",
Left = new Tree() {Value = "D", Left = new Tree() {Value = "G"}},
Right = new Tree() {Value = "E", Right = new Tree() {Value = "H"}}
};
tree.Right = new Tree() {Value = "C", Right = new Tree() {Value = "F"}};
return tree;
}
遍历:
递归实现:
public static void PreOrder(Tree tree)
{
if (tree == null)
return;
System.Console.WriteLine(tree.Value);
PreOrder(tree.Left);
PreOrder(tree.Right);
}