04Leetcode每日一题——二叉树的直径
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
代码
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) return 0;
int leftResult = (root.left==null)?0:diameterOfBinaryTree(root.left);
int rightResult = (root.right==null)?0:diameterOfBinaryTree(root.right);
int result = (root.left!=null || root.right != null) ? 1:0;
if(root.left!=null && root.right != null){
result = findDepth(root.left) + findDepth(root.right) + 2;
}
int depth = findDepth(root);
result = Math.max(result, leftResult);
result = Math.max(result, rightResult);
result = Math.max(result, depth);
return result;
}
public int findDepth(TreeNode node){
if(node.left == null && node.right == null) return 0;
int leftDepth = 0;
int rightDepth = 0;
leftDepth = (node.left==null)?leftDepth:1+findDepth(node.left);
rightDepth = (node.right==null)?rightDepth:1+findDepth(node.right);
return Math.max(leftDepth, rightDepth);
}
}