111. Minimum Depth of Binary Tree
来源:互联网 发布:九章算法班 编辑:程序博客网 时间:2024/06/06 21:06
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. 当节点的左右孩子有一个非空时,递归到空的孩子节点时,要根据是否有兄弟节点来决定返回值。
2. 如果一味地将空节点返回0,就会导致[1, 2]这种二叉树的最小深度为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) { return minDepth(root, false); } int minDepth(TreeNode *root, bool hasBrother) { if (!root) return hasBrother ? INT_MAX : 0; return 1 + min(minDepth(root->left, root->right != NULL), minDepth(root->right, root->left != NULL)); }};
0 0
- 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
- 【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
- redis networking通信协议的源码分析
- 数据结构课程设计——源代码
- QT中设置exe文件描述信息
- 欢迎使用CSDN-markdown编辑器
- 我对在开发板上开发程序的一些理解
- 111. Minimum Depth of Binary Tree
- 结构——表 & 链
- Git 学习看这篇就够了!
- 浏览器加载网页的顺序
- Android问题解决:Caused by: java.lang.UnsupportedOperationException: Can't convert to fraction: type=0x3
- Android 文件下载引擎,稳定、高效、简单易用:FileDownloader(结合okhttp)
- 【BZOJ 3926】[Zjoi2015]诸神眷顾的幻想乡 广义后缀自动机
- angularjs+文件上传 http头content-type字段变化
- cas单点登录与spring boot关联使用