-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[543]二叉树的直径.java
More file actions
75 lines (70 loc) · 1.68 KB
/
Copy path[543]二叉树的直径.java
File metadata and controls
75 lines (70 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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 {
// // 思路一:分配求出最深的左右节点之和,加起来,然后再递归,然后不断更新最大值
// public int diameterOfBinaryTree(TreeNode root) {
//
// if (root == null) {
// return 0;
// }
//
// int leftMax = depth(root.left);
// int rightMax = depth(root.right);
//
// int res = leftMax + rightMax;
// int maxSum = Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right));
//
// return Math.max(res, maxSum);
//
// }
//
// // 求出深度
// public int depth(TreeNode root) {
// if (root == null) {
// return 0;
// }
//
// int left = depth(root.left);
// int right = depth(root.right);
// int res = Math.max(left, right) + 1;
// return res;
// }
//
//
// }
// 思路二:
class Solution {
// 设置一个全局的变量
int maxSum = 0;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return maxSum;
}
// 求出深度
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
-+
int left = depth(root.left);
int right = depth(root.right);
// // 后序遍历位置顺便计算最大直径
maxSum = Math.max((left + right), maxSum);
return 1 + Math.max(left, right);
}
}
//leetcode submit region end(Prohibit modification and deletion)