I like to read this solution as a small machine: keep the useful information, throw away the noise. For 543. Diameter of Binary Tree, the solution in this repository is mainly a two pointers solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers, sliding window.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are depth, diameterOfBinaryTree, treeDepth.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(N)O(N). We visit every node once.
- Space: O(N)O(N), the size of our implicit call stack during our depth-first search.
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
03
04Example:
05Given a binary tree
06 1
07 / \
08 2 3
09 / \
10 4 5
11Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
12
13Note: The length of path between two nodes is represented by the number of edges between them.
14**/
15
16/**
17Approach #1: Depth-First Search [Accepted]
18Intuition
19
20Any path can be written as two arrows (in different directions) from some node, where an arrow is a path that starts at some node and only travels down to child nodes.
21
22If we knew the maximum length arrows L, R for each child, then the best path touches L + R + 1 nodes.
23
24Algorithm
25
26Let's calculate the depth of a node in the usual way: max(depth of node.left, depth of node.right) + 1. While we do, a path "through" this node uses 1 + (depth of node.left) + (depth of node.right) nodes. Let's search each node and remember the highest number of nodes used in some path. The desired length is 1 minus this number.
27**/
28
29/**
30Complexity Analysis
31
32Time Complexity: O(N)O(N). We visit every node once.
33
34Space Complexity: O(N)O(N), the size of our implicit call stack during our depth-first search.
35**/
36
37//Runtime: 16 ms, faster than 99.19% of C++ online submissions for Diameter of Binary Tree.
38//Memory Usage: 19.8 MB, less than 100.00% of C++ online submissions for Diameter of Binary Tree.
39/**
40 * Definition for a binary tree node.
41 * struct TreeNode {
42 * int val;
43 * TreeNode *left;
44 * TreeNode *right;
45 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
46 * };
47 */
48class Solution {
49public:
50 int ans;
51 int depth(TreeNode* node){
52 if(node == NULL) return 0;
53 int L = depth(node->left);
54 int R = depth(node->right);
55 ans = max(ans, L+R);
56 return max(L, R) + 1;
57 }
58 int diameterOfBinaryTree(TreeNode* root) {
59 ans = 0;
60 depth(root);
61 return ans;
62 }
63};
64
65//stack overflow
66/**
67class Solution {
68public:
69 int treeDepth(TreeNode* node){
70 if(node == NULL) return 0;
71 return 1 + max(treeDepth(node->left), treeDepth(node->right));
72 }
73 int diameterOfBinaryTree(TreeNode* root) {
74 if(root == NULL) return 0;
75 return max(
76 treeDepth(root->left) + treeDepth(root->right),
77 max(diameterOfBinaryTree(root->left),
78 diameterOfBinaryTree(root->right)));
79 }
80};
81**/
Cost