CShap 二叉树的逆向有序遍历 源代码
时间: 2023-11-06 22:04:38 浏览: 87
以下是C#的二叉树逆向有序遍历的源代码:
```
using System;
using System.Collections.Generic;
class Node
{
public int value;
public Node left;
public Node right;
public Node(int value)
{
this.value = value;
left = null;
right = null;
}
}
class BinaryTree
{
Node root;
public BinaryTree()
{
root = null;
}
public void Insert(int value)
{
Node newNode = new Node(value);
if (root == null)
{
root = newNode;
return;
}
Node current = root;
Node parent = null;
while (true)
{
parent = current;
if (value < current.value)
{
current = current.left;
if (current == null)
{
parent.left = newNode;
return;
}
}
else
{
current = current.right;
if (current == null)
{
parent.right = newNode;
return;
}
}
}
}
public void ReverseInorderTraversal()
{
if (root == null)
return;
Stack<Node> stack = new Stack<Node>();
Node current = root;
while (current != null || stack.Count > 0)
{
if (current != null)
{
stack.Push(current);
current = current.right;
}
else
{
current = stack.Pop();
Console.Write(current.value + " ");
current = current.left;
}
}
}
}
class Program
{
static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.Insert(50);
tree.Insert(30);
tree.Insert(20);
tree.Insert(40);
tree.Insert(70);
tree.Insert(60);
tree.Insert(80);
Console.Write("Reverse Inorder Traversal of Binary Tree: ");
tree.ReverseInorderTraversal();
}
}
```
这个程序创建了一个名为BinaryTree的类,它包含一个二叉树和两个方法。 Insert()方法用于将值插入二叉树中,ReverseInorderTraversal()方法用于进行逆向有序遍历,并在控制台上打印每个节点的值。
在Main()方法中,我们创建了一个BinaryTree对象,并插入了一些值。然后,我们调用ReverseInorderTraversal()方法,它将打印二叉树的逆向有序遍历。
阅读全文