2022-12-24 16:15:41 +08:00
|
|
|
/**
|
2023-04-23 19:36:07 +08:00
|
|
|
* File: binary_tree_dfs.cs
|
2022-12-24 16:15:41 +08:00
|
|
|
* Created Time: 2022-12-23
|
|
|
|
* Author: haptear (haptear@hotmail.com)
|
|
|
|
*/
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
namespace hello_algo.chapter_tree;
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
public class binary_tree_dfs {
|
2023-11-26 23:18:44 +08:00
|
|
|
List<int> list = [];
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
/* 前序遍历 */
|
2023-10-08 01:33:46 +08:00
|
|
|
void PreOrder(TreeNode? root) {
|
2023-02-08 22:18:02 +08:00
|
|
|
if (root == null) return;
|
2023-04-09 04:32:17 +08:00
|
|
|
// 访问优先级:根节点 -> 左子树 -> 右子树
|
2023-11-26 23:18:44 +08:00
|
|
|
list.Add(root.val!.Value);
|
2023-10-08 01:33:46 +08:00
|
|
|
PreOrder(root.left);
|
|
|
|
PreOrder(root.right);
|
2023-02-08 22:18:02 +08:00
|
|
|
}
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
/* 中序遍历 */
|
2023-10-08 01:33:46 +08:00
|
|
|
void InOrder(TreeNode? root) {
|
2023-02-08 22:18:02 +08:00
|
|
|
if (root == null) return;
|
2023-04-09 04:32:17 +08:00
|
|
|
// 访问优先级:左子树 -> 根节点 -> 右子树
|
2023-10-08 01:33:46 +08:00
|
|
|
InOrder(root.left);
|
2023-11-26 23:18:44 +08:00
|
|
|
list.Add(root.val!.Value);
|
2023-10-08 01:33:46 +08:00
|
|
|
InOrder(root.right);
|
2023-02-08 22:18:02 +08:00
|
|
|
}
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
/* 后序遍历 */
|
2023-10-08 01:33:46 +08:00
|
|
|
void PostOrder(TreeNode? root) {
|
2023-02-08 22:18:02 +08:00
|
|
|
if (root == null) return;
|
2023-04-09 04:32:17 +08:00
|
|
|
// 访问优先级:左子树 -> 右子树 -> 根节点
|
2023-10-08 01:33:46 +08:00
|
|
|
PostOrder(root.left);
|
|
|
|
PostOrder(root.right);
|
2023-11-26 23:18:44 +08:00
|
|
|
list.Add(root.val!.Value);
|
2023-02-08 22:18:02 +08:00
|
|
|
}
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
[Test]
|
2023-04-23 03:03:12 +08:00
|
|
|
public void Test() {
|
2023-02-08 22:18:02 +08:00
|
|
|
/* 初始化二叉树 */
|
|
|
|
// 这里借助了一个从数组直接生成二叉树的函数
|
2023-11-26 23:18:44 +08:00
|
|
|
TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]);
|
2023-02-08 22:18:02 +08:00
|
|
|
Console.WriteLine("\n初始化二叉树\n");
|
|
|
|
PrintUtil.PrintTree(root);
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
list.Clear();
|
2023-10-08 01:33:46 +08:00
|
|
|
PreOrder(root);
|
2023-04-21 14:59:22 +08:00
|
|
|
Console.WriteLine("\n前序遍历的节点打印序列 = " + string.Join(",", list));
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
list.Clear();
|
2023-10-08 01:33:46 +08:00
|
|
|
InOrder(root);
|
2023-04-21 14:59:22 +08:00
|
|
|
Console.WriteLine("\n中序遍历的节点打印序列 = " + string.Join(",", list));
|
2022-12-24 16:15:41 +08:00
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
list.Clear();
|
2023-10-08 01:33:46 +08:00
|
|
|
PostOrder(root);
|
2023-04-21 14:59:22 +08:00
|
|
|
Console.WriteLine("\n后序遍历的节点打印序列 = " + string.Join(",", list));
|
2022-12-24 16:15:41 +08:00
|
|
|
}
|
|
|
|
}
|