1, 543. Diameter of Binary Tree
维护左右子树的高度,同时更新结果,返回以该节点结束的最大长度。递归调用。

1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int res; 13 int work(TreeNode* root) { 14 if(!root) return 0; 15 int a = work(root->left), b = work(root->right); 16 res = max(res, a + b + 1); 17 return max(a, b) + 1; 18 } 19 int diameterOfBinaryTree(TreeNode* root) { 20 res = 0; 21 work(root); 22 if(res >= 1) res -= 1; 23 return res; 24 } 25 };
2. 538. Convert BST to Greater Tree
利用bst的有序性,一次遍历,同时维护后缀和,更新节点。递归调用。

1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int s; 13 void work(TreeNode* root) { 14 if(!root) return; 15 if(!root->left && !root->right) { 16 root->val += s; 17 s = root->val; 18 return; 19 } 20 if(root->right) work(root->right); 21 root->val += s; 22 s = root->val; 23 work(root->left); 24 } 25 TreeNode* convertBST(TreeNode* root) { 26 s = 0; 27 work(root); 28 return root; 29 } 30 };
3. 542. 01 Matrix
简单的bfs,初始为0的节点加入队列,然后更新相邻节点,直到最后的结果为空。

1 int dx[] = {1, -1, 0, 0}; 2 int dy[] = {0, 0, 1, -1}; 3 class Solution { 4 public: 5 6 int n, m; 7 bool check(int x, int y) { 8 if(x >= 0 && x < n && y >= 0 && y < m) return 1; 9 return 0; 10 } 11 vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { 12 n = matrix.size(); 13 m = matrix[0].size(); 14 typedef pair<int, int> pii; 15 vector<vector<int>> res(n, vector<int>(m, INT_MAX)); 16 queue<pii> q; 17 for (int i = 0; i < n; i++) { 18 for (int j = 0; j < m; j++) { 19 if(matrix[i][j] == 0) { 20 res[i][j] = 0; 21 q.push({i, j}); 22 } 23 } 24 } 25 int x, y, v; 26 while(!q.empty()) { 27 x = q.front().first, y = q.front().second; 28 q.pop(); 29 v = res[x][y]; 30 for (int i = 0; i < 4; i++) { 31 int cx = x + dx[i], cy = y + dy[i]; 32 if(check(cx, cy)) { 33 if(res[cx][cy] > v + 1) { 34 res[cx][cy] = v + 1; 35 q.push({cx, cy}); 36 } 37 } 38 } 39 } 40 return res; 41 } 42 };
4. 544. Output Contest Matches
一个队的rank在整个过程是不变的,都是第一个元素决定的,然后每次生成新节点,维护下顺序,第一个和最后一个合并,直到只剩一个为止。

1 class Solution { 2 public: 3 4 string findContestMatch(int n) { 5 vector<string> a; 6 for (int i = 0; i < n / 2; i++) { 7 stringstream ss; 8 ss << "(" << i + 1 << "," << (n - i) << ")"; 9 a.push_back(ss.str()); 10 } 11 vector<string> b; 12 int sz = a.size(); 13 while(a.size() > 1) { 14 b.clear(); 15 sz = a.size(); 16 for (int i = 0; i < sz / 2; i++) { 17 string t = "(" + a[i] + "," + a[sz - i - 1] + ")"; 18 b.push_back(t); 19 } 20 swap(a, b); 21 } 22 return a[0]; 23 } 24 };