题目描述
题目链接
https://leetcode.com/problems/diameter-of-binary-tree/
方法思路
Approach1: 双递归但是效率很低,这个方法太过直接粗暴
class Solution {
//Runtime: 13 ms, faster than 14.48%
//Memory Usage: 40.6 MB, less than 37.57%
public int diameterOfBinaryTree(TreeNode root) {
if(root == null || (root.left == null && root.right == null))
return 0;
int ans = 0;
//需要考虑只有左子树或者只有右子树的情况如:[1,2]
if(root.left != null && root.right != null)
ans = dfs(root) + Math.min(dfs(root.left), dfs(root.right)) + 1;
else
ans = dfs(root);
int left = diameterOfBinaryTree(root.left);
int right = diameterOfBinaryTree(root.right);
left = Math.max(left, right);
ans = Math.max(ans, left);
return ans;
}
public int dfs(TreeNode root){
if(root == null || (root.left == null && root.right == null))
return 0;
int left = dfs(root.left);
int right = dfs(root.right);
return Math.max(left, right) + 1;
}
}
Approach2: Depth-First Search
class Solution {
//Runtime: 3 ms, faster than 100.00%
//Memory Usage: 39.7 MB, less than 58.09%
int ans;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) return 0;
ans = 0;
depth(root);
return ans;
}
public int depth(TreeNode node) {
if (node == null) return 0;
int L = depth(node.left);
int R = depth(node.right);
ans = Math.max(ans, L+R);
return Math.max(L, R) + 1;
}
}