# C#LeetCode刷题之#104-二叉树的最大深度​​​​​​​（Maximum Depth of Binary Tree）

3
/ \
9   20
/        \
15        7

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Given binary tree [3,9,20,null,null,15,7],

3
/ \
9   20
/        \
15        7

return its depth = 3.

```public class Program {

public static void Main(string[] args) {
var root = new TreeNode(1) {
left = new TreeNode(2),
right = new TreeNode(3)
};

var res = MaxDepth(root);
Console.WriteLine(res);

res = MaxDepth2(root);
Console.WriteLine(res);

}

public static int MaxDepth(TreeNode root) {
//递归法，本示例无法使用尾递归
if(root == null) return 0;
var left = MaxDepth(root.left);
var right = MaxDepth(root.right);
return Math.Max(left, right) + 1;
}

public static int MaxDepth2(TreeNode root) {
//若为空，返回 0
if(root == null) return 0;
//定义结果
var res = 0;
//定义一个栈，存一个键值对，键为节点，值为节点的深度
var stack = new Stack<KeyValuePair<TreeNode, int>>();
//把根节点压入栈中，其深度为 1
stack.Push(new KeyValuePair<TreeNode, int>(root, 1));
//处理栈，条件为栈不为空，即当栈空时终止
while(stack.Any()) {
//弹出栈顶元素所记录
var top = stack.Pop();
//每次比较最大值并存入 res
res = Math.Max(res, top.Value);
//为左、右子节点的深度计数
if(top.Key.left != null) {
//若左子节点不为空，则将左子节点压入栈中，并将其深度值 +1
stack.Push(new KeyValuePair<TreeNode, int>(top.Key.left, top.Value + 1));
}
if(top.Key.right != null) {
//若右子节点不为空，则将右子节点压入栈中，并将其深度值 +1
stack.Push(new KeyValuePair<TreeNode, int>(top.Key.right, top.Value + 1));
}
}
//返回 res
return res;
}

public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

}```

```2
2```