Minimum Depth of Binary Tree (C + + binary tree minimum depth)

Problem-solving ideas:

(1) Use recursion

(2) Note that the minimum height of a node is the minimum height of the left and right subtrees + 1

(3) Note that if the height of one of the subtrees is 0, then the height of the other subtree + 1 is the minimum height of the node

/**
 * 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 dfs(root);
        else return 0;
    }

private:
    int dfs(TreeNode* node) {
        int l = node->left ? dfs(node->left) : 0;
        int r = node->right ? dfs(node->right) : 0;
        if (l==0) return r+1;
        if (r==0) return l+1;
        else return min(l,r)+1;
    }
};

 

Published 303 original articles · praised 277 · 420,000 views

Guess you like

Origin blog.csdn.net/coolsunxu/article/details/105531658
Recommended