Skip to content

Commit 3e046f1

Browse files
committed
Refactor MaxDepth method and add BuildTree method
Changed MaxDepth to a static method in MaximumDepthOfBinaryTree.cs for easier access. Added BuildTree method in ConstructBinaryTreeFromPreorderAndInorderTraversal.cs to construct a binary tree from preorder and inorder arrays, including null checks and recursive subtree construction. Added necessary using directives.
1 parent 758338a commit 3e046f1

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

101-110/104.MaximumDepthOfBinaryTree.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ namespace LeetCodeNote;
44

55
public static partial class Solution
66
{
7-
public int MaxDepth(TreeNode root)
7+
public static int MaxDepth(TreeNode root)
88
{
99
if (root == null) return 0;
1010

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
using System.Linq;
3+
4+
namespace LeetCodeNote;
5+
6+
public static partial class Solution
7+
{
8+
/// <summary>
9+
/// need more details and understanding
10+
/// </summary>
11+
/// <param name="preorder"></param>
12+
/// <param name="inorder"></param>
13+
/// <returns></returns>
14+
public static TreeNode BuildTree(int[] preorder, int[] inorder)
15+
{
16+
if (preorder is null || !preorder.Any() ||
17+
inorder is null || !inorder.Any()) return null;
18+
19+
TreeNode root = new TreeNode(preorder[0]);
20+
int middle = Array.IndexOf(inorder, preorder[0]);
21+
root.left = BuildTree(preorder[1..(middle + 1)], inorder[..middle]);
22+
root.right = BuildTree(preorder[(middle + 1)..], inorder[(middle + 1)..]);
23+
24+
return root;
25+
}
26+
}

0 commit comments

Comments
 (0)