-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumDepthOfBinaryTree104.cs
More file actions
68 lines (52 loc) · 1.48 KB
/
MaximumDepthOfBinaryTree104.cs
File metadata and controls
68 lines (52 loc) · 1.48 KB
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
namespace LeetCode;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class MaximumDepthOfBinaryTree104
{
public int MaxDepthRecursive(TreeNode root)
{
return MaxDepth(root, 0);
}
private int MaxDepth(TreeNode root, int depth)
{
if (root == null) return depth;
depth++;
int left = MaxDepth(root.left, depth);
int right = MaxDepth(root.right, depth);
return left > right ? left : right;
}
public int MaxDepth(TreeNode root)
{
if (root == null) return 0;
Queue<TreeNode> nodes = new Queue<TreeNode>();
int depth = 0;
nodes.Enqueue(root);
nodes.Enqueue(null);
while (nodes.Count > 0)
{
TreeNode current = nodes.Dequeue();
if (current != null)
{
if (current.left != null) nodes.Enqueue(current.left);
if (current.right != null)nodes.Enqueue(current.right);
}
if(current == null)
{
depth++;
if (nodes.Count > 0)
{
nodes.Enqueue(null);
}
}
}
return depth;
}
}