[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
- [leetcode] 111. Minimum Depth of Binary Tree 解题报告
- LeetCode解题报告 111. Minimum Depth of Binary Tree [easy]
- [Leetcode] 111. Minimum Depth of Binary Tree 解题报告
- [leetcode]111. Minimum Depth of Binary Tree@Java解题报告
- 【LeetCode】Minimum Depth of Binary Tree 解题报告
- LeetCode(111) Minimum Depth of Binary Tree解题报告
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Mac不连网怎么办,Mac上安装的VMware Fusion不连网怎么办(续篇)
- 新路程------imx6测试网卡phy
- 【LEET-CODE】9. Palindrome Number
- Ehcache 单例模式 探究
- 火狐浏览器所有历史版本下载地址
- [Leetcode] 111. Minimum Depth of Binary Tree 解题报告
- 七种方案解决JavaScript交换两个变量值的问题
- DOM
- 在Linux里读取UBOOT环境变量
- 阶乘除法
- c标签的使用if 和foreach一般使用
- 【angular2】端到端测试初步
- PhpStorm2016.3激活码
- Activity保存状态(四)