111. 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.我的答案(递归)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int min(TreeNode* root,int num){
        if(root->left == NULL && root->right == NULL)
            return num;
        if(root->left == NULL ||  root->right == NULL){
            TreeNode* t = (root->left!=NULL?root->left:root->right);
            return min(t,num+1);
        }else{
        int l = min(root->left, num+1);
        int r = min(root->right, num+1);
            return l<r?l:r;
        }
        
    }
    int minDepth(TreeNode* root) {
        if(!root)
        return 0;
        if(root->left == NULL && root->right==NULL)
        return 1;
        return min(root,1);
        
    }
};


2.别人的答案(递归)

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

3.别人的答案(BFS)

int minDepth(TreeNode* root) {
    if (root == NULL) return 0;
    queue<TreeNode*> Q;
    Q.push(root);
    int i = 0;
    while (!Q.empty()) {
        i++;
        int k = Q.size();
        for (int j=0; j<k; j++) {
            TreeNode* rt = Q.front();
            if (rt->left) Q.push(rt->left);
            if (rt->right) Q.push(rt->right);
            Q.pop();
            if (rt->left==NULL && rt->right==NULL) return i;
        }
    }
}


你可能感兴趣的:(LeetCode,C++,二叉树,bfs,recursion)