二叉树路径之和的最大值

上一题有路径有关,难度稍大。现在看个比较简单的题目。

题目:计算二叉树路径之和的最大值。

二叉树节点可以表示为:

private class BinaryTreeNode {
    int value;
    BinaryTreeNode left;
    BinaryTreeNode right;
}

虽然也涉及到了路径,但是并不要求记录具体路径节点。

public int maxPathSum(BinaryTreeNode root) {
    if (root == null) {
        return 0;
    }
    int childMax = Math.max(maxPathSum(root.left), maxPathSum(root.right));
    return root.value + childMax;
}

算法是二叉树递归中的后序遍历。与之类似的题目是求二叉树的高度,相当于是特殊情况。

public int height(BinaryTreeNode root) {
    if (root == null) {
        return 0;
    }
    int childMaxHeight = Math.max(height(root.left), height(root.right));
    return childMaxHeight + 1;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容