LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
2017-08-03 22:31
561 查看
二叉树最小深度:
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;返回右子树最小深度);结束递归的条件:左右子树都为空。
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; } };
相关文章推荐
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- [LeetCode] Minimum Depth of Binary Tree 二叉树最小深度
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- Leetcode Minimum Depth of Binary Tree 二叉树最小深度
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- [LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度
- Minimum Depth of Binary Tree 二叉树最小深度
- Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]
- leetcode Minimum&&Max Depth of Binary Tree 求树的最小&&最大深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- Minimum Depth of Binary Tree -- 二叉树的最小深度 DFS 加剪枝
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)