leecode-543-二叉树的直径

leecode-543-二叉树的直径

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = 0;
    
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return max;
    }
    // 辅助函数,求最大深度,任意节点所在最长路径等于左子树的最大深度 + 右子树的最大深度
    public int maxDepth(TreeNode root) {
        // base case
        if (root == null) return 0;
        
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        // 获得当前最长路径
        max = Math.max(max, left + right);
        
        return Math.max(left, right) + 1;
    }
}

leecode-543-二叉树的直径

上一篇:543. 二叉树的直径


下一篇:leetcode 543 二叉树的直径