题解 | #牛群的最长距离#

牛群的最长距离

https://www.nowcoder.com/practice/82848c6aa1f74dd1b95d71f3c35c74d5

考察二叉树的递归算法。利用深度优先搜索遍历根节点以及左右子树,返回其中路径的最大值就是最长的距离。对于每个节点需要先得到这个节点左右子树的最大距离,然后相加才是这个节点的最大距离。

完整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);
        return Math.max(left, right) + 1;
    }
}

全部评论

相关推荐

Twilight_m...:还是不够贴近现实,中关村那块60平房子200万怎么可能拿的下来,交个首付还差不多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务