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;
}
}
标签:right,TreeNode,int,max,543,leecode,二叉树,root,left 来源: https://blog.csdn.net/hmyqwe/article/details/111935045