R9-二叉树篇
左子树的深度+右子树的深度即可
但好像不行
思路:
对于每个节点,计算它的左子树深度和右子树深度相加的和,并更新最大值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ret;
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);
return ret;
}
private int dfs(TreeNode node){
if(node==null){
//下面的结果会自动+1,所以这里返回-1,对于叶子节点来说就是0
return -1;
}
int lLen=dfs(node.left)+1;
int rLen=dfs(node.right)+1;
ret=Math.max(ret,lLen+rLen);
//当前子树最大链长
return Math.max(lLen,rLen);
}
}