题目
二叉树的直径
(目前的做题思路是从CodeTop的简单题刷起)
题解
递归
时间复杂度:O(n)
空间复杂度:O(height) 递归的栈
/**
* 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 {
int dia=0;//直径
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return dia;
}
public int depth(TreeNode node){
if(node==null)
return 0;
int L=depth(node.left);//左子树直径
int R=depth(node.right);//右子树直径
dia=Math.max(dia,L+R);//更新直径=max[(左树高度-1)+(右树高度-1)+2,原直径]
return Math.max(L,R)+1;//左右子树谁的直径大选一个就行
}
}