問題:
https://leetcode.com/problems/minimum-depth-of-binary-tree/?tab=Description
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爲空,root左節點或者右節點爲空,root左右節點都不爲空。
參考C++代碼:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL) return 1+minDepth(root->right);
if(root->right==NULL) return 1+minDepth(root->left);
int l=minDepth(root->left);
int r=minDepth(root->right);
return l<r?l+1:r+1;
}
};