LeetCode-二叉树最小深度

2017-03-20  本文已影响50人  SincereDu

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.
先上代码

class Solution {
public:
    int run (TreeNode *root) {
        
        if (root == NULL) 
            return 0;
        if (root->left == NULL && root->right == NULL) 
            return 1;
        if (root->left == NULL) 
            return run(root->right) + 1;
        else if (root->right == NULL) 
            return run(root->left) + 1;
        else 
            return 1 + min(run(root->left), run(root->right));
    }
}

解题思路是<a href = "https://zh.wikipedia.org/wiki/%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2">深度优先搜索DFS</a>
严谨一些,我们先把极端的情况先处理一下

同理,稍微修改一下我们也可以求出二叉树的最大深度

int maxDepth(TreeNode *root)
{
    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}

😄递归很好使、

上一篇 下一篇

猜你喜欢

热点阅读