方法一,递归。时间复杂度O(n),空间复杂度O(logN),分几种情况讨论:
(1) 空节点。 直接返回 0;
(2) 左右节点都为空(当前节点不为空), 则当前是叶子节点,返回1。
(3) 左节点(或者右节点)为空, 则该节点不为叶子节点,直接返回右节点(左节点)的最小高度+1.
(4) 左右都不为空,返回左右子树中的最小高度+1。
class Solution {
public:
int minDepth(TreeNode *root) {
return minDepth(root, false);
}
int minDepth(TreeNode *root, bool hasSibling)
{
if(root == NULL)
return hasSibling? INT_MAX:0;
return std::min(minDepth(root->left, root->right),
minDepth(root->right, root->left)) + 1;
}
};
方法二,使用队列,逐层遍历并记录层数(深度),当某一层发现有一个叶子节点时,则停止遍历。
时间复杂度O(n),空间复杂度O(n)。
class Solution {
public:
int minDepth(TreeNode *root) {
if(!root) return 0;
queue<TreeNode*> queue;
queue.push(root);
queue.push(NULL);
int depth = 1;
while(!queue.empty()) {
TreeNode *cur = queue.front();
queue.pop();
if(cur) {
if(cur->left)
queue.push(cur->left);
if(cur->right)
queue.push(cur->right);
if(cur->left == NULL && cur->right == NULL)
break;
}else
{
if(!queue.empty())
{
queue.push(NULL);
depth++;
}
}
}
return depth;
}
};
方法三,使用栈,DFS遍历。时间复杂度O(n),空间复杂度O(logN)。在每个node进栈的时候,同时需要记录它所在的深度,因此stack中的格式为<node, depth>
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == NULL) return 0;
stack<pair<TreeNode*,int> > s;
int mindepth = INT_MAX;
s.push(make_pair(root,1));
while(!s.empty())
{
TreeNode *cur = s.top().first;
int depth = s.top().second;
s.pop();
//this may not be the leaf with minimum depth
//so here we cannot return
if(cur->left == NULL && cur->right == NULL)
mindepth = min(mindepth, depth);
if(cur->left != NULL && mindepth > depth)
s.push(make_pair(cur->left, depth+1));
if(cur->right!= NULL && mindepth > depth)
s.push(make_pair(cur->right, depth+1));
}
return mindepth;
}
};