mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-16 03:59:18 +08:00
fix(csharp): Modify method name to PascalCase, simplify new expression (#840)
* Modify method name to PascalCase(array and linked list) * Modify method name to PascalCase(backtracking) * Modify method name to PascalCase(computational complexity) * Modify method name to PascalCase(divide and conquer) * Modify method name to PascalCase(dynamic programming) * Modify method name to PascalCase(graph) * Modify method name to PascalCase(greedy) * Modify method name to PascalCase(hashing) * Modify method name to PascalCase(heap) * Modify method name to PascalCase(searching) * Modify method name to PascalCase(sorting) * Modify method name to PascalCase(stack and queue) * Modify method name to PascalCase(tree) * local check
This commit is contained in:
@@ -8,30 +8,30 @@ namespace hello_algo.chapter_divide_and_conquer;
|
||||
|
||||
public class build_tree {
|
||||
/* 构建二叉树:分治 */
|
||||
public TreeNode dfs(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
|
||||
public TreeNode Dfs(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
|
||||
// 子树区间为空时终止
|
||||
if (r - l < 0)
|
||||
return null;
|
||||
// 初始化根节点
|
||||
TreeNode root = new TreeNode(preorder[i]);
|
||||
TreeNode root = new(preorder[i]);
|
||||
// 查询 m ,从而划分左右子树
|
||||
int m = inorderMap[preorder[i]];
|
||||
// 子问题:构建左子树
|
||||
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
|
||||
root.left = Dfs(preorder, inorderMap, i + 1, l, m - 1);
|
||||
// 子问题:构建右子树
|
||||
root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
|
||||
root.right = Dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
|
||||
// 返回根节点
|
||||
return root;
|
||||
}
|
||||
|
||||
/* 构建二叉树 */
|
||||
public TreeNode buildTree(int[] preorder, int[] inorder) {
|
||||
public TreeNode BuildTree(int[] preorder, int[] inorder) {
|
||||
// 初始化哈希表,存储 inorder 元素到索引的映射
|
||||
Dictionary<int, int> inorderMap = new Dictionary<int, int>();
|
||||
Dictionary<int, int> inorderMap = new();
|
||||
for (int i = 0; i < inorder.Length; i++) {
|
||||
inorderMap.TryAdd(inorder[i], i);
|
||||
}
|
||||
TreeNode root = dfs(preorder, inorderMap, 0, 0, inorder.Length - 1);
|
||||
TreeNode root = Dfs(preorder, inorderMap, 0, 0, inorder.Length - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class build_tree {
|
||||
Console.WriteLine("前序遍历 = " + string.Join(", ", preorder));
|
||||
Console.WriteLine("中序遍历 = " + string.Join(", ", inorder));
|
||||
|
||||
TreeNode root = buildTree(preorder, inorder);
|
||||
TreeNode root = BuildTree(preorder, inorder);
|
||||
Console.WriteLine("构建的二叉树为:");
|
||||
PrintUtil.PrintTree(root);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user