leetCode 111. Minimum Depth of Binary Tree 二叉树问题
111. 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.
思路:
mine思路:
1.采用后序遍历非递归方式,找到叶子节点,记录当时栈内元素的个数到容器中。
2.最后从容器中选择最小的一个输出。
代码如下:
/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode(intx):val(x),left(NULL),right(NULL){}*};*/classSolution{public:intminDepth(TreeNode*root){intiMinDepth;vector<int>depths;stack<TreeNode*>s;TreeNode*p,*q;q=NULL;p=root;if(!root)return0;while(p!=NULL||s.size()>0){while(p!=NULL){s.push(p);p=p->left;}if(s.size()>0){p=s.top();if(NULL==p->left&&NULL==p->right){depths.push_back(s.size());}if((NULL==p->right||p->right==q)){q=p;s.pop();p=NULL;}elsep=p->right;}}iMinDepth=depths[0];for(inti=0;i<depths.size();i++){if(depths[i]<iMinDepth){iMinDepth=depths[i];}}returniMinDepth;}};
参考其他:http://www.cnblogs.com/bakari/p/4126693.html
有两种求解的思路,一种采用DFS的思想,一种采用BFS的思想,如下代码所示:
structTreeNode{intval;TreeNode*left;TreeNode*right;TreeNode(intx):val(x),left(NULL),right(NULL){}};//采用DFS的思想intmaxDepth(TreeNode*root){if(NULL==root)return0;intl=maxDepth(root->left);intr=maxDepth(root->right);returnl>r?l+1:r+1;//以上这两种方式有一种更简便的方法//return1+max(maxDepth(root->left),maxDepth(root->right));}//采用BFS的方法,引入队列intmaxDepth(TreeNode*root){if(NULL==root)return0;queue<TreeNode*>que;intnCount=1;intnDepth=0;//记录队列里面每一层上的元素que.push(root);while(!que.empty()){TreeNode*pTemp=que.front();que.pop();nCount--;if(pTemp->left)que.push(pTemp->left);if(pTemp->right)que.push(pTemp->right);if(nCount==0){nDepth++;nCount=que.size();}}returnnDepth;}
2016-08-07 10:12:37
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。