LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
来源:互联网 发布:哪里有im域名 编辑:程序博客网 时间:2024/05/19 23:13
二叉树最小深度:
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(特殊情况:单一子树为空时,对应最小深度为0,但是并非叶子节点,此时返回非空子树的深度。递归至E节点:左子树为空,最小深度为0;右子树非空,最小深度为1;返回右子树最小深度);结束递归的条件:左右子树都为空。
class TreeNode{public:TreeNode(){}TreeNode(int _val){val=_val;}TreeNode* left;TreeNode* right;int val;};class Solution {public: int run(TreeNode *root) { if(root==nullptr){return 0;} int m=run(root->left); int n=run(root->right); if(m==0||n==0)//单一子树为空时,返回非空的节点深度加1 {return m+n+1;} else { return m>n?n+1:m+1;} }};遍历非递归解法:初始化,根节点入队列,当前层节点个数,最小深度depth。只要队列不为空,取队首节点,出队,当前层size减1,当前节点左右非空子树入队;若左右子树都为空,返回最小深度depth。如果当前层size为0,说明上一层节点遍历完了,更新size,最小深度depth加1。
#include<queue>
class Solution {public: int run(TreeNode *root) { int depth=1;//最小深度 int treeSize=0;//当前层节点个数 if(root==nullptr) return 0; queue<TreeNode*>row; row.push(root); treeSize=row.size(); TreeNode * temp; while(!row.empty()) { temp=row.front(); row.pop(); treeSize--; if(temp->left==nullptr&&temp->right==nullptr) return depth; if(temp->left!=nullptr) row.push(temp->left); if(temp->right!=nullptr) row.push(temp->right); if (treeSize==0)//当前层节点遍历结束 { treeSize=row.size();//下一层的节点个数 depth++;//最小深度加1 } } return depth; }};
阅读全文
0 0
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- LeetCode: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 二叉树的最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- LeetCode OJ 之 Minimum Depth of Binary Tree(二叉树的最小深度)
- leetCode 111.Minimum Depth of Binary Tree(二叉树最小深度) 解题思路和方法
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- [Java代码] [Leetcode] Maximum and 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】Minimum Depth Of Binary Tree二叉树的最小深度
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- 【HDU1233】还是畅通工程(最小生成树-水题)
- PAT 5-19
- 最大连续子数列和 模板
- 关于i++ 跟++i 的区别。
- 字节输入流
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- 用递归方式实现逆序输出
- Unity UGUI 原理篇(四):Event System Manager 事件與觸發
- 新手上路系列6:内存错误
- 内存溢出和内存泄漏的区别
- 数据存储技术取得突破,存储数据需“开源”更需“节流”
- A
- Handler sendMessage的message保存在哪?
- 计蒜客 逃跑 (bfs+预处理)