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.
思想:递归即可
注意事项: 如果left或者right为空,需要忽略;
- public int minDepth(TreeNode root) {
- if(root == null) return 0;
- if(root.left == null && root.right == null) return 1;
- if(root.left == null) return minDepth(root.right)+1;
- if(root.right == null) return minDepth(root.left)+1;
- return Math.min(minDepth(root.left),minDepth(root.right))+1;
- }
C++代码:
- int minDepth(TreeNode *root) {
- if(root==NULL) return 0;
- int leftmin = minDepth(root->left);
- int rightmin = minDepth(root->right);
- if(leftmin * rightmin != 0) return min(leftmin,rightmin)+1;
- else if(rightmin==0) return leftmin+1;
- else if(leftmin==0) return rightmin+1; // notice whether the left tree is null or the right tree is null
- }