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.
注意: 叶子的返回条件是 root->left == NULL and root ->right == NULL
1 class Solution { 2 public: 3 int minDepth(TreeNode* root) { 4 if (root == NULL) 5 return 0; 6 if (root ->left == NULL && root ->right == NULL) 7 return 1; 8 if (root ->left != NULL && root ->right == NULL) 9 return dfs(root->left,2); 10 if (root ->left == NULL && root ->right != NULL) 11 return dfs(root->right,2); 12 return min(dfs(root->left,2),dfs(root->right,2)); 13 } 14 int dfs(TreeNode* root, int depth) 15 { 16 if (root->left == NULL && root->right == NULL) 17 return depth; 18 if (root ->left != NULL && root ->right == NULL) 19 return dfs(root->left,depth+1); 20 if (root ->left == NULL && root ->right != NULL) 21 return dfs(root->right,depth+1); 22 return min(dfs(root->left,depth+1),dfs(root->right,depth+1)); 23 } 24 };
Maximum
1 class Solution { 2 public: 3 int maxDepth(TreeNode* root) { 4 if (root == NULL) 5 return 0; 6 if (root->left || root->right) 7 return maxDepth(root->left) + maxDepth(root->right) +1 ; 8 return max(maxDepth(root->left),maxDepth(root->right)) +1; 9 10 } 11 };
浙公网安备 33010602011771号