Форум программистов, компьютерный форум, киберфорум
C# .NET
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 1
Регистрация: 05.11.2012
Сообщений: 25
1

Изменить обход по дереву

30.05.2013, 12:08. Показов 726. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Помогите пожалуйста изменить обход по дереву из обхода в глубину(сверху вниз), на обход в ширину (слева направо).
Класс с полями
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace InformationSystemKadri
{
    /// <summary>
    /// Node of tree, which contains information about object of tree and next leafs.
    /// </summary>
    public class BinaryTreeNode<T>
    {
 
        #region Fields
 
        /// <summary>
        /// Data in node.
        /// </summary>
        private T _data;
 
        /// <summary>
        /// Left node.
        /// </summary>
        private BinaryTreeNode<T> leftNode;
 
        /// <summary>
        /// Right node.
        /// </summary>
        private BinaryTreeNode<T> rightNode;
 
        /// <summary>
        /// Parent node.
        /// </summary>
        private BinaryTreeNode<T> parentNode;
        
        /// <summary>
        /// Offset - left to right (0 is center)
        /// </summary>
        private int _offset;                 
 
        /// <summary>
        /// Depth - top to bottom.
        /// </summary>
        private int _depth;
 
        #endregion
 
        /// <summary>
        /// Constructor with parameters.
        /// </summary>
        /// <param name="data">Data.</param>
        public BinaryTreeNode(T data)
        {
            _data = data;
        }
 
        #region Properties        
 
        public BinaryTreeNode<T> Left
        {
            get { return leftNode; }
            set { leftNode = value; }
        }
 
        public BinaryTreeNode<T> Right
        {
            get { return rightNode; }
            set { rightNode = value; }
        }
 
        public BinaryTreeNode<T> Parent
        {
            get { return parentNode; }
            set { parentNode = value; }
        }
 
        public T Data
        {
            get { return _data; }
            set { _data = value; }
        }
 
        public int Offset
        {
            get { return _offset; }
            set { _offset = value; }
        }
 
        public int Depth
        {
            get { return _depth; }
            set { _depth = value; }
        }
 
        #endregion
                     
    }
}
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
 
namespace InformationSystemKadri.Classes
{    
 
    /// <summary>
    /// Generic class, which allow to work with information with help of binary tree.
    /// </summary>
    /// <typeparam name="T">Type of data, what conatains node of tree.</typeparam>
    public class BinaryTree<T> where T : IComparable
    {
        /// <summary>
        /// Root of tree.
        /// </summary>
        private BinaryTreeNode<T> _center;        
 
        /// <summary>
        /// Property for access to root of tree.
        /// </summary>
        public BinaryTreeNode<T> Center
        {
            get { return _center; }
        }               
 
        /// <summary>
        /// Method for adding new node to the tree.
        /// </summary>
        /// <param name="data">New data.</param>
        /// <returns>New node.</returns>
        public BinaryTreeNode<T> Add(T data)
        {
            if (_center == null)
            {
                _center = new BinaryTreeNode<T>(data);
                _center.Depth = 1;
                _center.Offset = 0;
                return _center;
            }
            else
            {
                BinaryTreeNode<T> current = _center;
                BinaryTreeNode<T> next;
                int nodeDepth = _center.Depth;
                int nodeOffset = _center.Offset;
                while (true)
                {
                    nodeDepth++;
                    if (data.CompareTo(current.Data) <= 0)
                    {
                        nodeOffset--;
                        next = current.Left;
                        if (next == null)
                        {
                            current.Left = new BinaryTreeNode<T>(data);                            
                            current.Left.Parent = current;
                            if (nodeDepth == current.Depth)
                            {
                                nodeDepth++;
                            }
                            current.Left.Depth = nodeDepth;                            
                            current.Left.Offset = nodeOffset;
                            return current.Left;                            
                        }
                    }
                    else
                    {
                        nodeOffset++;
                        next = current.Right;
                        if (next == null)
                        {
                            current.Right = new BinaryTreeNode<T>(data);
                            current.Right.Parent = current;
                            if (nodeDepth == current.Depth)
                            {
                                nodeDepth++;
                            }
                            current.Right.Depth = nodeDepth;
                            current.Right.Offset = nodeOffset;
                            return current.Right;                            
                        }
                    }
                    current = next;
                }
 
            }
        }
 
        /// <summary>
        /// Remove node from the tree.
        /// </summary>
        /// <param name="node"></param>
        public void Remove(BinaryTreeNode<T> node)
        {
            // If node is null.
            if (node == null) return;            
 
            // If children are null.
            if (node.Right == null && node.Left == null)
            {                
                if (node == node.Parent.Left) node.Parent.Left = null;
                else node.Parent.Right = null;
            }            
            else 
            {                                                           
                if (node == node.Parent.Left)
                {
                    node.Parent.Left = node.Left;
                    if (node.Left == null)
                    {
                        node.Parent.Left = node.Right;
                        SetDepth(node.Parent, node.Parent.Depth, node.Parent.Offset);
                    }
                    else
                    {
                        node.Parent.Left.Depth = node.Parent.Depth + 1;
                        BinaryTreeNode<T> rightBranch = MostRightNode(node.Parent);
                        rightBranch.Right = node.Right;
                        SetDepth(rightBranch.Right, rightBranch.Depth + 1, rightBranch.Offset - 1);
                    }
                }
                else
                {
                    node.Parent.Right = node.Right;
                    if (node.Right == null)
                    {
                        node.Parent.Right = node.Left;
                        SetDepth(node.Parent, node.Parent.Depth, node.Parent.Offset);
                    }
                    else
                    {
                        node.Parent.Right.Depth = node.Parent.Depth + 1;
                        BinaryTreeNode<T> leftBranch = MostLeftNode(node.Parent);
                        leftBranch.Left = node.Left;
                        SetDepth(leftBranch.Left, leftBranch.Depth + 1, leftBranch.Offset + 1);
                    }
                }                
            }
        }
 
        /// <summary>
        /// Finds the most right node of the given node childs.
        /// </summary>
        /// <param name="node">Parent node.</param>
        /// <returns>Most right node.</returns>
        private BinaryTreeNode<T> MostRightNode(BinaryTreeNode<T> node)
        {
            if (node.Right != null)
                return MostRightNode(node.Right);
            else return node;            
        }
 
        /// <summary>
        /// Finds the most left node of the given node childs.
        /// </summary>
        /// <param name="node">Parent node.</param>
        /// <returns>Most left node.</returns>
        private BinaryTreeNode<T> MostLeftNode(BinaryTreeNode<T> node)
        {   
            if (node.Left != null)
                return MostLeftNode(node.Left);
            else return node;
        }
 
        /// <summary>
        /// Bypassing tree(recursion method).
        /// </summary>
        /// <param name="node">Parent node.</param>
        /// <param name="data">Data, what needs to find.</param>
        /// <returns>Finded node, or null.</returns>
        public BinaryTreeNode<T> TreeBypass(BinaryTreeNode<T> node, T data)
        {
            // Compare two objects.
            if (Treatment(node.Data, data) == true) return node;
 
            // If left node is not null.
            if (node.Left != null && data.CompareTo(node.Data) <= 0)
                return TreeBypass(node.Left, data);
 
            // If right node is not null.
            if (node.Right != null && data.CompareTo(node.Data) > 0)
                return TreeBypass(node.Right, data);
            return null;            
        }
 
        /// <summary>
        /// Bypasing tree(recursion method), and format list of nodes.
        /// </summary>
        /// <param name="node">Parent node.</param>
        /// <param name="nodes">List of nodes.</param>
        public void TreeBypass(BinaryTreeNode<T> node, List<BinaryTreeNode<T>> nodes)
        {
            nodes.Add(node);
            if (node.Left != null)
                TreeBypass(node.Left, nodes);
            if (node.Right != null)
                TreeBypass(node.Right, nodes);
        }
 
        /// <summary>
        /// Compare two data objects.
        /// </summary>
        /// <param name="data1">First data object.</param>
        /// <param name="data2">Second data object.</param>
        /// <returns>Returns true if data1 equals data2, otherwise - false.</returns>
        private bool Treatment(T data1, T data2)
        {
            if (data1.Equals(data2))            
                return true;            
            else return false;                   
        }                       
 
        /// <summary>
        /// Change data of node.
        /// </summary>
        /// <param name="node">Node, which data needs to change.</param>
        /// <param name="data">New data.</param>
        /// <param name="radical">If changes key - true, otherwise - false.</param>
        public void ChangeData(BinaryTreeNode<T> node, T data, bool radical = true)
        {
            if (node != _center && radical == true)
            {
                Remove(node);
                Add(data);
            }
            else
            {
                node.Data = data;
            }
        }       
 
        /// <summary>
        /// Set depth, for graphical output of tree.
        /// </summary>
        /// <param name="node">Parent node.</param>
        /// <param name="depth">Depth of node.</param>
        /// <param name="offset">Offset of node.</param>
        private void SetDepth(BinaryTreeNode<T> node, int depth, int offset)
        {            
            if (node != null)
            {
                node.Depth = depth;
                node.Offset = offset;
                if (node.Left != null)
                {
                    SetDepth(node.Left, depth + 1, offset - 1);
                }
                if (node.Right != null)
                {
                    SetDepth(node.Right, depth + 1, offset + 1);
                }                
            }            
        }        
    }
}
Добавлено через 8 часов 9 минут
Ну или хотя бы наводку дайте в каком методе менять. Или теории какой подкиньте по префиксным и инфиксным обходам. Просто нормального объяснения в нете на C# не смог найти
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
30.05.2013, 12:08
Ответы с готовыми решениями:

Обход по дереву
Доброго вам дня всем! Есть некоторые вопросы по одной задаче из теории. Прошу помочь в них...

Как изменить размер дрегого окна IE? (обход блокировки PopUp)
Привет All! Подскажите: у меня в форме при нажатии кнопки submit открывается другое окно...

Рекурсивный обход. Не могу сделать табуляцию. Обход с выводом имен файлов
Задание простое, ну по крайней мере на первый взгляд. Написать скрипт обхода вложенных директорий с...

Переход по дереву
Извиняюсь за глупый вопрос. Ребят, подскажите, как делается так чтобы при нажатии на дерево...

0
30.05.2013, 12:08
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
30.05.2013, 12:08
Помогаю со студенческими работами здесь

Выжигатель по дереву
Стыдно канешно с такими вопросами обращаться к форумчанам.И всё таки надо сделать выжигатель по...

Поиск по дереву
По задании надо сделать поиск по дереву и найти минимальный возраст.

Поиск по дереву
Основная суть - это гениалогическое дерево и это реализовал. Но также есть дополнительное...

Разница между понятиями "Обход в прямом направлении" и "Итерационный прямой обход"
Ребятаа, обьясните чем различается: Обход в прямом направлении и Итерационный прямой обход ...

Итератор по бинарному дереву
Всем привет! Помогите пожалуйста! Пишу бинарное дерево, нужно реализовать итератор по нему. Не...

treeView навигация по дереву
Добрый день. Есть treeView, у которого может быть любое кол-во узлов, уровней вложенности. При этом...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru