Minimum Depth of Binary Tree
来源:互联网 发布:nba直播数据统计 编辑:程序博客网 时间:2024/05/18 01:49
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.
Subscribe to see which companies asked this question
一种就是计算左子树和右子树深度的时候,判断是否等于0,如果等于0,说明该子树不存在,深度赋值为最大值。
第二种就是判断左子树或右子树是否为空,若左子树为空,则返回右子树的深度,反之返回左子树的深度,如果都不为空,则返回左子树和右子树深度的最小值
任何一个节点的深度 都得加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; if (root->left == NULL && root->right == NULL) return 1; int leftDepth = minDepth(root->left); int rightDepth = minDepth(root->right); //判断一个节点是不是单支的如果是则该节点深度由他的一支决定,如果左为空,什么由右支决定 if (leftDepth == 0) return rightDepth + 1; else if (rightDepth == 0) return leftDepth + 1; else return min(leftDepth, rightDepth) + 1; }};
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- sublime 快捷键
- js原生rotate函数
- abababababababababababababababababababababababababababababababababababababababababababababababababab
- Divisibility
- HDOJ 1290 献给杭电五十周年校庆的礼物
- Minimum Depth of Binary Tree
- 257.leetcode Binary Tree Paths(easy)[二叉树深度路径遍历]
- 设计模式---行为类型---解释器
- 【 CodeForces 612A 】 The Text Splitting
- 水仙花数——java
- 自定义View之利用组合View实现复用
- mysql处理字符串的两个绝招:substring_index,concat
- A - Divisibility
- Lucene搜索引擎入门写法