Minimum Depth of Binary Tree (leetcode)
来源:互联网 发布:如何选冰箱 知乎 编辑:程序博客网 时间:2024/05/16 10:25
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.
https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
使用二叉树非递归后续遍历得到从根节点到叶子节点的最小长度。
/** * 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) {return 0;}std::stack<TreeNode *> mystack;bool is_node_visited = false;TreeNode *curr = root;TreeNode *prev_visited = NULL;int min_depth = 0;int curr_depth = 0;do {while (curr && !is_node_visited) {mystack.push(curr);++curr_depth;curr = curr->left;}curr = mystack.top();if (curr->right && curr->right != prev_visited) {curr = curr->right;is_node_visited = false;} else {//it's the leaf node, get the depth;if (!curr->left && !curr->right) {if (min_depth == 0) {min_depth = curr_depth;} else {min_depth = std::min(min_depth, curr_depth);}}prev_visited = curr;is_node_visited = true;mystack.pop();--curr_depth;}} while (!mystack.empty());return min_depth; }};
0 0
- 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
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 客服管理系统--售后服务、商品评论管理、咨询邮件回复
- Tomcat下配置数据源链接数据库
- 【LeetCode】-Construct Binary Tree from Preorder and Inorder Traversal
- pandas小记:pandas数据规整化-分组合并及重塑
- bzoj1207:[HNOI2004]打鼹鼠[DP]
- Minimum Depth of Binary Tree (leetcode)
- yahoo 笔试题
- awk和grep退出状态问题
- Oracle 11g服务详细介绍及哪些服务是必须开启的?
- Oracle中tnsping 主机名/Ip 显示TNS-12541: TNS:no listener
- Android中最简单的分享功能
- ubunt安装 无法将grub-efi-amd64-signed软件包安装到/target/
- 更新一个表的字段值等于另一个表的字段值
- hdu2795 Billboard