美文网首页
111. Minimum Depth of Binary Tre

111. Minimum Depth of Binary Tre

作者: 刘小小gogo | 来源:发表于2018-08-26 12:13 被阅读0次
    image.png

    解法一:递归

    /**
     * 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 minDepth(TreeNode* root) {
            if(root == NULL) return 0;
            int left = minDepth(root->left);
            int right = minDepth(root->right);    
            if(root->left == NULL) return 1 + right;
            if(root->right == NULL) return 1 + left;
            return 1 + min(left, right);
        }
    };
    

    解法二:bfs
    注意的是:如何一层记一个数,用for循环来遍历q;

    /**
     * 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 minDepth(TreeNode* root) {
            if(root == NULL) return 0;
            queue<TreeNode*> q;
            q.push(root);
            int depth = 0;
            while(!q.empty()){
                int k = q.size();
                depth++;
                for(int i = 0; i < k; i++){
                    TreeNode* cur = q.front();
                    q.pop();
                    if(cur->left == NULL && cur->right == NULL) return depth;
                    if(cur->left) q.push(cur->left);
                    if(cur->right) q.push(cur->right);
                }
            }
            return 0;
        }
    };
    

    相关文章

      网友评论

          本文标题:111. Minimum Depth of Binary Tre

          本文链接:https://www.haomeiwen.com/subject/tnqoiftx.html