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. 每进入一层用一个变量(这里是levelNum)记录当前从根节点到这一层节点的节点数
2. 当到达叶子节点的时候,就记录当前最小深度overall
2. 当所有的叶子节点都到达一遍之后,就得到了最终最小深度overall。
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == nullptr) return 0;
int overall = INT_MAX;
int levelNum = 0;
minD(root, overall, levelNum);
return overall;
}
void minD(TreeNode *node, int &overall, int levelNum)
{
if(node == nullptr) return;
levelNum++;
minD(node->left, overall, levelNum);
minD(node->right, overall, levelNum);
if(node->left==nullptr && node->right==nullptr)
overall = min(overall,levelNum);
}
};
//2014-2-16 update
int minDepth(TreeNode *root)
{
if (!root) return 0;
if (!root->left && !root->right) return 1;
int L = root->left? minDepth(root->left)+1:INT_MAX;
int R = root->right? minDepth(root->right)+1:INT_MAX;
return min(L, R);
}
分享到:
相关推荐
原创:leetcode 111. 二叉树的最小深度记住:最小深度和最大深度方法不同。* Definition for a binary tree node.in
144.Binary_Tree_Preorder_Traversal二叉树的前序遍历【LeetCode单题讲解系列】
145.Binary_Tree_Postorder_Traversal二叉树的后序遍历【LeetCode单题讲解系列】
leetcode的题目:Balanced Binary Tree
leetcode 数据结构题目中的答案,已经调试,直接运行,求二叉树的最小深度
BinaryTree.py是一个方便的工具,它可以构建和显示编码时所需的二叉树 演示 您需要在使用之前导入该类 import BinaryTree as bt 从值/对象列表或二叉树构造二叉树 t1 = bt.BinaryTree([1,2,3,4,5,'#',6,7,'#','#','#...
我的个人微信公众号:Microstrong 微信公众号ID:MicrostrongAI 微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的...102. Binary Tree Leve
94.Binary_Tree_Inorder_Traversal二叉树的中序遍历【LeetCode单题讲解系列】
1.1 树的最小深度Given a binary tree, find its minimum depth.The minimum depth is the n
leetcode卡leetcode_practices_learncard_binarytree 我的 leetcode 练习二叉树学习卡在 100% 完成 :) 我的 Java8 备忘单:
示例:返回它的最小深度 2.Related Topics树深度优先搜索广度优先搜索题目代码* Definition for a binary tree nod
leetcode卡leetcode 二叉树卡片 LeetCode 二叉树卡片问题的章节智解
二叉树前序遍历,leetcode
前几天在练习算法的时候,发现leetcode提供了一个对用户友好的tree-visualizer,可以把a转成二叉树,然后显示出来。 树可视化器的一个惊人之处在于它可以调整每个节点的位置,这样树就不会占用太多空间。 当我试图...
leetcode 树节点二叉树的直径 给定一棵二叉树,您需要计算树的直径长度。 二叉树的直径是树中任意两个节点之间最长路径的长度。 此路径可能会或可能不会通过根。 Example: Given a binary tree 1 / \ 2 3 / \ 4 5 ...
leetcode 不会二叉树倾斜 给定一棵二叉树,返回整棵树的倾斜度。 树节点的倾斜度定义为所有左子树节点值的总和与所有右子树节点值的总和之间的绝对差。 空节点的倾斜度为 0。 整棵树的倾斜度定义为所有节点倾斜度的...
原创:leetcode 107. 二叉树的层次遍历 II【队列】* Definition for a binary tree node.
leetcode伪代码merge-two-binary-tree 题目解读: 题目来源: 原文: Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the...
104.maximum-depth-of-binary-tree (二叉树的最大深度) 105.construct-binary-tree-from-preorder-and-inorder-traversal (从前序与中序遍历序列构造二叉树) 106.construct-binary-tree-from-inorder-and-postorder-...
LeetCodeLeetCode solutions(Java)树Minimum Depth of Binary Tree栈evaluate-reverse-polish-notation穷举max-points-on-a-line链表sort-list排序insertion-sort-list树binary-tree-postorder-traversal树binary-...