minimum-depth-of-binary-tree——二叉树遍历、链表、广度优先

本文介绍了一种求解二叉树最小深度的算法实现。该算法通过广度优先搜索遍历二叉树,找到从根节点到最近叶节点的最短路径长度。

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 class Solution {
 2 public:
 3     typedef TreeNode* tree;
 4     int run(TreeNode *root) {
 5         if(!root)
 6             return 0;
 7         queue<tree> q;
 8         q.push(root);
 9         tree cur,last;
10         int level=1;
11         last=q.back();
12         while(q.size()){
13             cur=q.front();
14             q.pop();
15             if(cur->left==NULL&&cur->right==NULL)
16                 break;
17             if(cur->left!=NULL)
18                 q.push(cur->left);
19             if(cur->right!=NULL)
20                 q.push(cur->right);
21             if(last==cur){
22                 level++;
23                 last=q.back();
24             }
25         }
26         return level;
27         
28     }
29 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值