Leetcode 111. Minimum Depth of Binary Tree

 

 

 我们要想知道最小深度,我们只需要知道根结点在的层级吖。这样思考是不是很方便。把每个根结点的层级加入map,取map的第一位,就是最小深度啦

/**
 * 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) {
        map<int, bool> m;
        preOrder(root, 0, m);
        if(!root) return 0;
        return m.begin()->first + 1;
    }
    void preOrder(TreeNode* root, int level, map<int,bool>& m) {
        if(root == NULL) return;
        if(root->left == NULL && root->right == NULL) m[level] = true;
        preOrder(root->left, level+1, m);
        preOrder(root->right, level+1, m);
    }

};

 

posted @ 2020-02-07 04:58  SteveYu  阅读(103)  评论(0编辑  收藏  举报