LeetCode | 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.

题目解析:

一开始看成求出最小深度的题目,但是要找到从根到叶节点的路径,比如,只有一个根和一个叶的树,那么深度不是1,而是2!因此当便利某一个节点的左右子树的时候,如果一个深度返回0,就返回另一个深度值+1。这样的话,就能求出正确结果。

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(root == NULL)
            return 0;
        int Ldep = minDepth(root->left);
        int Rdep = minDepth(root->right);
        if(Ldep == 0)
            return Rdep+1;
        if(Rdep == 0)
            return Ldep+1;

        return Ldep > Rdep ? (Rdep+1) : (Ldep+1);
    }
};

代码这样写更漂亮:

class Solution {
public:
    int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root)
        {
            if(root->left == NULL && root->right == NULL)
                return 1;
            else if(root->left == NULL)
                return minDepth(root->right) + 1;
            else if(root->right == NULL)
                return minDepth(root->left) + 1;
            return min(minDepth(root->left), minDepth(root->right)) + 1;
        }
        return 0;
     
    }
};

方案二:

条条大路通罗马,也可以暴力求解的方式,暴力求解,递归到每一个叶子节点,记录深度,然后维护一个最小的值即可。此算法效率不高,若存在一个叶子节点很矮,而其他叶子节点很深的情况,需要遍历到所有深的结点。

class Solution {  
public:  
    int minDepth(TreeNode *root) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
        if(root == NULL)  
            return 0;  
        int depth = INT_MAX;  
        int tmp = 1;  
        recursion(root, tmp, depth);  
        return depth;  
    }  
    void recursion(TreeNode *root, int tmp, int &depth)  
    {  
        if(root->left == NULL && root->right == NULL)  
        {  
            if(tmp < depth)  
                depth = tmp;  
            return ;  
        }  
        if(root->left)  
        {  
            recursion(root->left, tmp + 1, depth);  
        }  
        if(root->right)  
        {  
            recursion(root->right, tmp + 1, depth);  
        }  
    }  
};  

点赞