在上篇《简单二叉树实现》的基础上实现二叉树的反转
目的
如下图
代码
- 相比之前的代码添加反转函数
//反转
public void Reversal() {
reversal(ref root);
Debug.Log("反转");
}
private void reversal(ref binary_tree_Node node)
{
if(node != null){
if (node.LeftNode == null && node.RightNode == null)
{
return;
}
binary_tree_Node leftNode = node.LeftNode;
node.LeftNode = node.RightNode;
node.RightNode = leftNode;
reversal(ref node.LeftNode);
reversal(ref node.RightNode);
}
}
- 所有代码
using UnityEngine;
using System.Collections;
using System;
/// <summary>
/// 最简单的二叉树
/// wc 2017/5/27
/// </summary>
public class binary_tree_Node
{
public binary_tree_Node LeftNode;
public binary_tree_Node RightNode;
public int value;
public binary_tree_Node() { }
}
public class binary_tree {
public binary_tree_Node root;
private string values = "";
//插入
public void Insert(int value) {
insert(ref root,value);
}
private void insert(ref binary_tree_Node node, int value)
{
if(node == null){
node = new binary_tree_Node();
node.LeftNode = null;
node.RightNode = null;
node.value = value;
return;
}
if (value <= node.value)
{
insert(ref node.LeftNode, value);
}
else if (value > node.value)
{
insert(ref node.RightNode, value);
}
}
//前序遍历
public void Preorder()
{
values = "";
preorder(root);
Debug.Log("前序遍历: " + values);
}
private void preorder(binary_tree_Node node)
{
if (node != null)
{
values += node.value + ",";
preorder(node.LeftNode);
preorder(node.RightNode);
}
}
//中序遍历
public void Inorder()
{
values = "";
inorder(root);
Debug.Log("中序遍历: " + values);
}
private void inorder(binary_tree_Node node)
{
if (node != null)
{
inorder(node.LeftNode);
values += node.value + ",";
inorder(node.RightNode);
}
}
//后序遍历
public void PostOrder() {
values = "";
postOrder(root);
Debug.Log("后序遍历: " + values);
}
private void postOrder(binary_tree_Node node)
{
if (node != null)
{
postOrder(node.LeftNode);
postOrder(node.RightNode);
values += node.value + ",";
}
}
//删除
public void DeleteTree() {
deleteTree(ref root);
Debug.Log("删除树");
}
public void deleteTree(ref binary_tree_Node node)
{
if(node != null){
binary_tree_Node nodeLeft = node.LeftNode;
binary_tree_Node nodeRight = node.RightNode;
deleteTree(ref nodeLeft);
deleteTree(ref nodeRight);
node = null;
}
}
//反转
public void Reversal() {
reversal(ref root);
Debug.Log("反转");
}
private void reversal(ref binary_tree_Node node)
{
if(node != null){
if (node.LeftNode == null && node.RightNode == null)
{
return;
}
binary_tree_Node leftNode = node.LeftNode;
node.LeftNode = node.RightNode;
node.RightNode = leftNode;
reversal(ref node.LeftNode);
reversal(ref node.RightNode);
}
}
}
public class TestTree : MonoBehaviour
{
void Start()
{
binary_tree tree = new binary_tree();
string rands = "";
for (int i = 0; i < 8; i++)
{
int random = UnityEngine.Random.Range(0, 100);
tree.Insert(random);
rands += random + ",";
}
print("原始数列: " + rands);
tree.Preorder();
tree.Inorder();
tree.PostOrder();
tree.Reversal();//反转
tree.Preorder();
tree.Inorder();
tree.PostOrder();
}
}