题目:
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.
解题思路:
1,若树为空返回0
2,若树没有左子树,返回右子树的深度+1
3,若树没有右子树,返回左子树的深度+1
4,否则,返回min(左子树的深度,右子树的深度) + 1
代码:
1 /** 2 * Definition for binary tree 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 minDepth(TreeNode *root) { 13 if (root == NULL) return 0; 14 15 if (root->left == NULL) return minDepth(root->right) + 1; 16 else if (root->right == NULL) return minDepth(root->left) + 1; 17 else return min(minDepth(root->left), minDepth(root->right)) + 1; 18 } 19 };