天天看點

leetcode-111. Minimum Depth of Binary Tree

  • 平時練習一下leetcode
  • 先根據牛課網上題練習,同步leetcode官網

題目

  • 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.

思路

  • 本題要注意最小深度與最大深度的差別:對于最大深度,不需要考慮目前子樹是否為單子樹(即一側樹深度為0)的情況,即最大深度一直等于左右子樹的最大值;對于最小深度,需要考慮目前子樹是否為單子樹的情況,對于雙子樹,其最小深度為左右子樹的最小值,對于單子樹,其最小深度為左右深度的最大值(因為一側的子樹為0).

Nowcoder

class Solution {
public:
    int run(TreeNode *root) {  //葉子結點才記錄深度,然後不斷更新
        if(root==nullptr)
            return 0;
        int l_depth=0,r_depth=0;
       
        l_depth=run(root->left);
        r_depth=run(root->right);
        
        if(l_depth==0)
            return r_depth+1;
        if(r_depth==0)
            return l_depth+1;
        if(l_depth<r_depth)
            return l_depth+1;
        else 
            return r_depth+1;
    }
};
           

leetcode

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

           

C/C++基本文法學習

STL

C++ primer

繼續閱讀