1
+ // 第一种方案,使用简单递归进行处理,虽然过了,但是明显很慢,加入备忘录之后提升也不是很明显
2
+
3
+ // Runtime: 56 ms, faster than 8.09% of C++ online submissions for Diameter of Binary Tree.
4
+ // Memory Usage: 35.5 MB, less than 7.41% of C++ online submissions for Diameter of Binary Tree.
5
+
6
+ /* *
7
+ * Definition for a binary tree node.
8
+ * struct TreeNode {
9
+ * int val;
10
+ * TreeNode *left;
11
+ * TreeNode *right;
12
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
13
+ * };
14
+ */
15
+ class Solution
16
+ {
17
+ public:
18
+ int diameterOfBinaryTree (TreeNode* root)
19
+ {
20
+ if (root == nullptr )
21
+ return 0 ;
22
+
23
+ int a = getDepth (root->left ) + getDepth (root->right );
24
+ int b = diameterOfBinaryTree (root->left );
25
+ int c = diameterOfBinaryTree (root->right );
26
+
27
+ return max (a, max (b, c));
28
+ }
29
+ private:
30
+ unordered_map<TreeNode*, int > hashmap;
31
+
32
+ int getDepth (TreeNode* root)
33
+ {
34
+ if (root == nullptr )
35
+ return 0 ;
36
+
37
+ if (hashmap.find (root) == hashmap.end ())
38
+ {
39
+ int left = getDepth (root->left );
40
+ int right = getDepth (root->right );
41
+
42
+ hashmap.insert (root, max (left, right) + 1 );
43
+ }
44
+ return hashmap.at (root);
45
+ }
46
+ };
47
+
48
+ // 第2种方案,速度提升还是非常明显的
49
+ // Runtime: 12 ms, faster than 68.92% of C++ online submissions for Diameter of Binary Tree.
50
+ // Memory Usage: 19.6 MB, less than 92.59% of C++ online submissions for Diameter of Binary Tree.
51
+
52
+ /* *
53
+ * Definition for a binary tree node.
54
+ * struct TreeNode {
55
+ * int val;
56
+ * TreeNode *left;
57
+ * TreeNode *right;
58
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
59
+ * };
60
+ */
61
+ class Solution
62
+ {
63
+ public:
64
+ int diameterOfBinaryTree (TreeNode* root)
65
+ {
66
+ getDepth (root);
67
+ return res;
68
+ }
69
+ private:
70
+ int res = 0 ;
71
+
72
+ int getDepth (TreeNode* root)
73
+ {
74
+ if (root == nullptr )
75
+ return 0 ;
76
+
77
+ int left = getDepth (root->left );
78
+ int right = getDepth (root->right );
79
+
80
+ res = max (res, left + right);
81
+
82
+ return max (left, right) + 1 ;
83
+ }
84
+ };
0 commit comments