[Leetcode] 111. Minimum Depth of Binary Tree 解题报告

来源:互联网 发布:投资返利网站源码 编辑:程序博客网 时间:2024/05/29 19:40

题目

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.

思路

1、深度优先搜索:分别计算左子树的最小高度和右子树的最小高度,然后总的最小高度就是左子树最小高度和右子树最小高度的最小值加1。但是需要注意当左子树为空时,它不会构成一条路径的,此时不能参与最小高度的计算。右子树同理。

2、广度优先搜索:深度优先搜索的缺点是需要计算出来所有的最短路径,然后返回最小值。但实际上不需要计算所有的最短路径,广度优先搜索刚好可以解决这一问题。我们采用广度优先搜索逐层遍历节点,一旦发现叶子节点,就可以立刻返回当前叶子结点的高度(因为我们逐层遍历时,叶子所处的高度总是单调递增的)。

代码

1、深度优先搜索:

/** * 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 == NULL) {            return 0;        }        int min_depth_left = root->left? minDepth(root->left) : INT_MAX;        int min_depth_right = root->right? minDepth(root->right) : INT_MAX;        int min_depth = min(min_depth_left, min_depth_right);        if (min_depth == INT_MAX) {            return 1;        }        else {            return min_depth + 1;        }    }};

2、广度优先搜索:

/** * 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 == NULL) {            return 0;        }        int depth = 0;        queue<TreeNode*> q;        q.push(root);        q.push(NULL);        while (!q.empty()) {            TreeNode *node = q.front();            q.pop();            if (node == NULL) {                ++depth;                if (!q.empty())                    q.push(NULL);            }            else {                if (!node->left && !node->right) {                    return depth + 1;                }                else {                    if (node->left)                        q.push(node->left);                    if (node->right)                        q.push(node->right);                }            }        }        return depth;    }};

0 0
原创粉丝点击