DFS: 111. Minimum Depth of Binary Tree
来源:互联网 发布:android chroot linux 编辑:程序博客网 时间:2024/05/16 02:58
这个题一开始我是按照求最大深度算的,只是把max改成min,发现大错特错。例如[1, 2]这个树就通不过。所以这次不能一次只看一个结点,一次需要看两层。如果左右子树都是NULL的才是叶子节点,左右子树有一个不是NULL他就不是叶子节点。我的代码:
/** * 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; if(root->left == NULL && root->right == NULL) return 1; else if(root->left != NULL && root->right != NULL) return min(minDepth(root->left), minDepth(root->right)) + 1; else if(root->left != NULL) return minDepth(root->left) + 1; else return minDepth(root->right) + 1; } };我这是把子树的所有情况全都写了一遍,肯定又写麻烦了,看看别人写的:
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)); }};
阅读全文
0 0
- DFS: 111. Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - DFS
- leetcode dfs Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree(DFS)
- [leetcode][tree][dfs] 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
- 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- Python(Mac版)通过PyCharmCE2017.1.2安装各种第三方包(以pygame为例)
- 顺序表应用5:有序顺序表归并
- 欢迎使用CSDN-markdown编辑器
- keytool.exe的详解(参数)、命名行生成keystore、java代码生成keystore
- 使用 Gitbook+disqus
- DFS: 111. Minimum Depth of Binary Tree
- 在HTML中添加背景音乐
- XJOIWeek 3 奋斗总结
- 机器学习算法-层次聚类AGNES
- IDA sp-analysis failed 不能F5的 解决方案
- 程序包databinding不存在的各种坑。
- Activiti工作流学习总结
- 直方图
- MATLAB数字图像处理(3)滤波