08.16
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
DFS (Depth First Search)
1 int minDepth(struct TreeNode* root) { 2 int leftMin, rightMin, min; 3 4 if (root == NULL) { 5 return 0; 6 } 7 leftMin = minDepth(root->left); 8 rightMin = minDepth(root->right); 9 if (leftMin == 0) { 10 min = rightMin; 11 } 12 else if (rightMin == 0) { 13 min = leftMin; 14 } 15 else { 16 min = leftMin < rightMin ? leftMin : rightMin; 17 } 18 return (min + 1); 19 }
耗时9ms。
看到这个解法https://discuss.leetcode.com/topic/8723/my-4-line-java-solution后,修改如下,耗时6ms。耗时节省33%的关键在于将两个if合并为一个if,可能这样生成的指令较少。
int minDepth(struct TreeNode* root) { int leftMin, rightMin; if (root == NULL) { return 0; } leftMin = minDepth(root->left); rightMin = minDepth(root->right); if (leftMin == 0 || rightMin == 0) { return leftMin + rightMin + 1; } else { return (leftMin < rightMin ? leftMin : rightMin) + 1; } }
BFS(Breadth First Search)
同样耗时9ms,采用类似如上修改后,耗时为6ms。我采用的不是典型的队列。
int minDepth(struct TreeNode* root) { struct TreeNode** nodeRow; int depth, len, size, i, j; if (root == NULL) { return 0; } size = 1024; nodeRow = malloc(sizeof(struct TreeNode*) * size); nodeRow[0] = root; len = 1; for (depth = 1; ; depth++){ for (i = 0, j = len; i < len; i++) { if (nodeRow[i]->left == NULL) { if (nodeRow[i]->right == NULL) { goto done; } nodeRow[i] = nodeRow[i]->right; } else { if (nodeRow[i]->right != NULL) { if (j >= size) { size *= 2; nodeRow = realloc(nodeRow, sizeof(struct TreeNode*) * size); /* error checking */ } nodeRow[j++] = nodeRow[i]->right; } nodeRow[i] = nodeRow[i]->left; } } len = j; } done: free(nodeRow); return depth; }
int minDepth(struct TreeNode* root) { struct TreeNode** nodeRow; struct TreeNode* lChild, * rChild; int depth, len, size, i, j, flag; if (root == NULL) { return 0; } size = 1024; nodeRow = malloc(sizeof(struct TreeNode*) * size); nodeRow[0] = root; len = 1; j = len; for (depth = 1; ; depth++){ for (i = 0; i < len; i++) { flag = (nodeRow[i]->left == NULL ? 0 : 2) | (nodeRow[i]->right == NULL ? 0 : 1); switch(flag) { case 3: if (j >= size) { size *= 2; nodeRow = realloc(nodeRow, sizeof(struct TreeNode*) * size); /* error checking */ } nodeRow[j++] = nodeRow[i]->right; nodeRow[i] = nodeRow[i]->left; break; case 2: nodeRow[i] = nodeRow[i]->left; break; case 1: nodeRow[i] = nodeRow[i]->right; break; default: /* least probability */ goto done; } } len = j; } done: free(nodeRow); return depth; }
6ms的排名是33.11% (Your time beats 33.11% of c submissions),不知道进一步怎么优化。
时间: 2024-10-08 03:04:42