LeetCode-二叉树最小深度

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));
    }
}

解题思路是深度优先搜索DFS
严谨一些,我们先把极端的情况先处理一下

  • 1 、为空的情况
  • 2 、左或者右子树为空的情况
  • 3 、我们需要编码处理的情况(递归算出结果)

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

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

递归很好使、

你可能感兴趣的:(LeetCode-二叉树最小深度)