树 求树的最小深度、最大深度

一、二叉树的最小深度

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) return 0;
        int l = 0, r = 0;
        if(root->left)  l = run(root->left);
        if(root->right)  r = run(root->right);
        if(root->left && root->right) return min(l, r)+1;
        else return l+r+1;

    }
};

解法二:

Class Solution {

public:
    int run(TreeNode *root) {
        if(!root) return 0;
        if(!root->left)  return run(root->right)+1;
        if(!root->right)  return run(root->left)+1;
        return min(run(root->right), run(root->left))+1;       
    }
};

二、二叉树的最大深度

链接:https://www.nowcoder.com/questionTerminal/8a2b2bf6c19b4f23a9bdb9b233eefa73
来源:牛客网

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

同上述最小深度方法类似,也可用两种方法求解:

class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        int l = 0, r = 0;
        if(root->right) r = maxDepth(root->right);
        if(root->left) l = maxDepth(root->left);
        return max(l, r)+1;
    }
};
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        if(root->right && root->left) 
            return max(maxDepth(root->left), maxDepth(root->right))+1;
        if(root->right) return maxDepth(root->right)+1;
        if(root->left) return maxDepth(root->left)+1;
        return 1;
    }
};

你可能感兴趣的:(Leetcode,C++)