题目考察的知识点

考察递归深度遍历二叉树

题目解答方法的文字分析

递归计算各个子树的深度,在这个中间更新最大深度,由左右子树和与之前的最大深度作比较。具体细节参看代码。

本题解析所用的编程语言

使用Java语言解决

完整且正确的编程代码

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {

    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型
     */
    int max = 0;
    public int diameterOfBinaryTree (TreeNode root) {
        // write code here
        dfs(root);
        return max;
    }
    
    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        max = Math.max(max, left + right); //更新max 因为有可能左+右得到最大长度
        return Math.max(left, right) + 1; //返回当前子树的最大长度
    }
}