Minimum Depth of Binary Tree

方法一,递归。时间复杂度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;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值