二叉树的最大深度
难度:简单
题目描述
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例1
输入: root = [3,9,20,null,null,15,7]
输出: 3
示例2
输入: root = [1,null,2]
输出: 2
题解
遍历每一个子树存下最大值,每遍历到最后的子叶和最大值进行比较
遍历结束之后的答案即为所得
想法代码
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;
}
}
class Solution
{
public static void Main(string[] args)
{
TreeNode root = new TreeNode(3)
{
left = new TreeNode(9),
right = new TreeNode(20)
{
left = new TreeNode (15),
right = new TreeNode (7)
}
};
Solution solution = new Solution();
Console.WriteLine(solution.MaxDepth(root));
}
int max = 0;
public int MaxDepth(TreeNode root)
{
BackTrack(root, 0, 0);
return max;
}
public void BackTrack(TreeNode root, int maxt,int tmp)
{
maxt = max;
if (root == null)
{
if (maxt < tmp)
{
max = tmp;
tmp = 0;
}
return;
}
BackTrack(root.left, maxt, tmp+1);
BackTrack(root.right, maxt, tmp+1);
}
}