LeetCode 111.二叉树最小深度

111.二叉树最小深度

剪枝前

剪枝后

C++ 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void  recu(TreeNode * root,std::vector<int> & path, int & tMin) 
    {
        //end  
         if(!root) return;
      //收集结果 
        if( !root->left && !root->right) 
        {
            // for(auto & t: path) std::cout   << t << " ";
            //   std::cout << std::endl;
            if(tMin> path.size()+1 ) tMin= path.size() +1;
           return ;
        }

        //for   剪枝   
      //  if( path.size() +1 < tMin )
        {
            path.emplace_back(root->val);
            recu(root->left, path,tMin);
            path.pop_back();

        }
       //  if( path.size() +1 <  tMin )
         {
            path.emplace_back(root->val);
            recu(root->right, path,tMin);
            path.pop_back();
         }


    }
    int minDepth(TreeNode* root) {

      if(!root)  return 0;
      int tMin=INT32_MAX;
      std::vector<int> path;
      recu(root,path,tMin);
      return tMin;
    }
};

posted @ 2021-02-01 13:22  boyang987  阅读(33)  评论(0编辑  收藏  举报