-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiameter-of-binary-tree.cpp
More file actions
89 lines (60 loc) · 1.96 KB
/
diameter-of-binary-tree.cpp
File metadata and controls
89 lines (60 loc) · 1.96 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 三刷,快速AC
int diameterOfBinaryTree(TreeNode* root){
if(!root) return 0;
res=1;
dfs(root);
return res-1;
}
int dfs(TreeNode* root){
if(!root) return 0;
int l=dfs(root->left);
int r=dfs(root->right);
res=max(res,l+r+1);
return max(l,r)+1;
}
//二刷竟然觉得难,做了很久,AC的思路感觉也不太好,应该是做麻烦了。
int res;
int diameterOfBinaryTree2(TreeNode* root) {
res=0;
helper(root);
return res;
}
int helper(TreeNode* root) { //返回的是本节点所能拥有的最长路径的长度,但不是转折点
if(!root) return 0;
if(!root->left && !root->right) return 0;
int count=0; //标记是否有两个儿子。
if(!root->left || !root->right) count=1;
int left=helper(root->left);
int right=helper(root->right);
res=max(res,left+right+2-count); //查看以本节点为转折点,所能拥有的最长路径。
cout<<root->val<<" "<<left<<" "<<right<<endl;
return max(left,right)+1;
}
//一刷,水题。
int result=-1;
int diameterOfBinaryTree1(TreeNode* root) {
if(!root) return 0;
part(root);
return result-1;
}
int part(TreeNode* root){ //返回的是最多节点数目。
if(!root) return 0;
int left=part(root->left);
int right=part(root->right);
int length=left+right+1;
//cout<<root->val<<" "<<length<<endl;
result=max(result,length);
return 1+max(left,right);
}
};