[C++]LeetCode: 30 Minimum Depth of Binary Tree

本文探讨了二叉树最小深度的两种算法实现:递归深度优先搜索(DFS)及非递归广度优先搜索(BFS)。通过两种方法求解从根节点到最近叶节点的最短路径。

题目:

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.

Anwser 1 :递归的方法 DFS

思路:分别计算根结点的左子树和右子树的最短depth,然后判断,如果左右子树都非空,则返回较小的depth。如果左/右子树有一个为空,则返回右/左的最小depth.

Attention: 

1. 题目要求一定是根结点到最近叶结点的depth,一定要遍历到叶结点。 所以和Maximum Depth of Binary Tree递归方式不一样。需要判断左右子树是否为空。

2. if(root == NULL) return 0; 是递归介绍的条件,一定不能忘记。

AC Code:

/**
 * Definition for binary tree
 * 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;
        
        int leftDepth = minDepth(root->left);
        int rightDepth = minDepth(root->right);
        
        if(leftDepth != 0 && rightDepth != 0) return min(leftDepth, rightDepth) + 1;
        else if(rightDepth == 0) return leftDepth + 1;   //如果没有右子树
        else if(leftDepth == 0) return rightDepth + 1;   //如果没有左子树
        
    }
};

Anwser 1 :非递归的方法 BFS IN queue

思路:level-order traversal and record current level depth, when meet a node which both child is null then return, no need to go farther。

Attention: 初始深度若根结点非空,为1 注意和Maximum Depth of Binary Tree构造的区别,算法不一样。

AC Code:

/**
 * Definition for binary tree
 * 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;
        
        queue<TreeNode*> Current;
        Current.push(root);
        queue<TreeNode*> Next;
        //初始深度若根结点非空,为1 注意和Maximum Depth of Binary Tree构造的区别,算法不一样。
        int depth = 1;
        
        while(!Current.empty())
        {
            while(!Current.empty())
            {
                TreeNode* node = Current.front();
                Current.pop();
                if(node->left == NULL && node->right == NULL)   return depth;
                if(node->left) Next.push(node->left);
                if(node->right) Next.push(node->right);
            }
            
            queue<TreeNode*> t;   //初始化Next,并将Next赋给Current.总是保存当前这一层节点。
            Current = Next;
            Next = t;
            depth++;
        }
        
        return depth;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值