LeetCode :: 2.Minimum Depth of Binary Tree [树类题目分析]
来源:互联网 发布:山下智久石原里美 知乎 编辑:程序博客网 时间:2024/06/13 04:05
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.
作为树分类的第二篇,寻找最浅的那片叶子。这里是一个后序遍历的过程。PS:无论中序、前序、后序,都是一种DFS(深度优先搜索,其实这里应该叫深度优先遍历好像形象一些>.<)。
顺带一提,如果要做BFS的话按以下6步来实现:1.初始化一个队列,根节点入队;2当队列为非空时,循环执行步骤3到步骤5,否则执行6;3出队列取得一个结点,访问该结点;4若该结点的左子树为非空,则将该结点的左子树入队列;5若该结点的右子树为非空,则将该结点的右子树入队列;
好像是因为程序本身很简单,所以没啥说的了。
/** * Definition for binary tree * 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 leftMin = minDepth(root -> left); int rightMin = minDepth(root -> right); if (leftMin == 0) //这里的头两个if是在左、右子树其中之一缺失的时候执行, return rightMin + 1; //如果没有两个判断语句,那么会错误地把没有子树那一边认为是min。 else if(rightMin == 0) return leftMin + 1; else return min(leftMin, rightMin) + 1; }};
0 0
- LeetCode :: 2.Minimum Depth of Binary Tree [树类题目分析]
- LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree
- LeetCode算法题目:Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree 理解分析
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- C#中4个常用的集合
- 编译vlc for android遇到的坑爹事
- android Timer与TimerTask的相关操作
- 大规模数据相似度计算时,解决数据倾斜的问题的思路之一(分块思想)
- 嵌入式笔试题
- LeetCode :: 2.Minimum Depth of Binary Tree [树类题目分析]
- C#treeView控件单击事件选中节点的问题
- CSS BoxModel 官方解读
- 1064. Complete Binary Search Tree
- tar命令备忘
- USACO 1.2.2 Milking Cows
- KMP(SOJ2652)
- Ruby学习笔记_super
- heritrix 下载、安装、配置