Leetcode P0111"Minimum Depth of Binary Tree" 题解

2020/09/08 Leetcode

博文中会简要介绍Leetcode P0111题目分析及解题思路。

“Minimum Depth of Binary Tree”是一道比较基础的题目,利用深度优先搜索,这里采取递归回溯的方法,每次获取当前树结点的左右子树高度,然后取其中的最小值。需要注意的是,若是非叶子结点的树结点,要注意若其左或者有子树不存在,则不存在的子树高度要设置为正无穷,以保证所有高度都是根结点到叶子结点的高度

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.

Note: A leaf is a node with no children.

以下是Java的题解代码实现。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        
        return this.traverse(root);
    }
    private int traverse(TreeNode curr) {
        if (curr.left == null && curr.right == null)
            return 1;
        
        int leftHeight = Integer.MAX_VALUE, rightHeight = Integer.MAX_VALUE;
        if (curr.left != null)
            leftHeight = this.traverse(curr.left);
        if (curr.right != null)
            rightHeight = this.traverse(curr.right);
        
        return Math.min(leftHeight, rightHeight)+1;
    }
}

以下是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:
    int minDepth(TreeNode* root) {
        if (!root)
            return 0;
        
        if (!root->left && !root->right)
            return 1;
        
        int lh = INT_MAX, rh = INT_MAX;
        if (root->left)
            lh = this->minDepth(root->left);
        if (root->right)
            rh = this->minDepth(root->right);
        
        return min(lh, rh)+1;
    }
};

Search

    Table of Contents