博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Minimum Depth of Binary Tree
阅读量:4150 次
发布时间:2019-05-25

本文共 1372 字,大约阅读时间需要 4 分钟。

struct TreeNode {	int val;	TreeNode *left;	TreeNode *right;	TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {	//find the minimum step of a tree, bfs works at most timepublic:	int BFS(TreeNode* root)	{		if(!root) 			return 0;        queue
> q; q.push(make_pair(root, 1)); while(!q.empty()) { TreeNode* curNode = q.front().first; int curStep = q.front().second; q.pop();//note here if(!curNode->left && !curNode->right) return curStep; if(curNode->left) q.push(make_pair(curNode->left, curStep+1)); if(curNode->right) q.push(make_pair(curNode->right, curStep+1)); } } int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function return BFS(root); }};

second time

/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == NULL) return 0;                if(root->left == NULL) return minDepth(root->right)+1;        else if(root->right == NULL) return minDepth(root->left)+1;        else return min(minDepth(root->left), minDepth(root->right))+1;    }};

转载地址:http://rlxti.baihongyu.com/

你可能感兴趣的文章
两个linux内核rootkit--之二:adore-ng
查看>>
两个linux内核rootkit--之一:enyelkm
查看>>
关于linux栈的一个深层次的问题
查看>>
rootkit related
查看>>
配置文件的重要性------轻化操作
查看>>
又是缓存惹的祸!!!
查看>>
为什么要实现程序指令和程序数据的分离?
查看>>
我对C++ string和length方法的一个长期误解------从protobuf序列化说起(没处理好会引起数据丢失、反序列化失败哦!)
查看>>
一起来看看protobuf中容易引起bug的一个细节
查看>>
无protobuf协议情况下的反序列化------貌似无解, 其实有解!
查看>>
make -n(仅列出命令, 但不会执行)用于调试makefile
查看>>
makefile中“-“符号的使用
查看>>
go语言如何从终端逐行读取数据?------用bufio包
查看>>
go的值类型和引用类型------重要的概念
查看>>
求二叉树中结点的最大值(所有结点的值都是正整数)
查看>>
用go的flag包来解析命令行参数
查看>>
来玩下go的http get
查看>>
队列和栈的本质区别
查看>>
matlab中inline的用法
查看>>
如何用matlab求函数的最值?
查看>>