首页 技术 正文
技术 2022年11月10日
0 收藏 427 点赞 2,813 浏览 1487 个字

problem description:

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.

problem analysis:

第一步,设计演算法:遍历一棵树的方法有两种,BFS and DFS,思考了下,BFS是一圈一圈的扩张出去,而这个problem是计算最小的深度,所以BFS可能更适合这个problem。

1.root is the layer 1

2.search out the node in layer 2 by layer1

3.check whether there is a leaf in layer 2: if true, return current layer; if false, continue iteration until finding a leaf.

第二步,设计data structure。在BFS中,优先考虑的data structure是queue,可是在c language中,并没有现成的queue container。那么how to solve this small problem。使用了两个数组,两个index,用来表示数组的长度,这样就实现了一个长度可变的数组。一个数组用来store父节点,另外一个数组用来store孩子节点。当一次iteration结束后,将孩子节点数组的内容移动到父节点数组,孩子节点数组清除为0,在code中,将孩子节点数组的index置为0表示数组当前值无效。

 /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     struct TreeNode *left;  *     struct TreeNode *right;  * };  */ int minDepth(struct TreeNode* root) {     //special case 1     ;     //special case 2     ;     int numOfParent, numOfChildren;     ;     ];     ];     //initialization     parent[] = root;     numOfParent = ;     numOfChildren = ;     //start iteration from root     while(true)     {         //calculate children         ;         ; i<numOfParent; i++)         {             if(parent[i]->left) {children[counter]=parent[i]->left; counter++;}             if(parent[i]->right) {children[counter]=parent[i]->right; counter++;}         }         //store the length of children in numOfChildren, children's level in layer         numOfChildren = counter;         layer++;         //check whether there is a leaf in children         ; k<numOfChildren; k++)         {             if( (children[k]->left==NULL) && (children[k]->right==NULL) ) return layer;         }         //preparation for next iteration         numOfParent = numOfChildren;         ; m<numOfChildren; m++)         {             parent[m] = children[m];         }         numOfChildren = ;     } }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293