A very simple question, but I still want to talk about it. Minimum depth. I soon thought of bfs and sequence traversal. I did not write much code during my undergraduate course, but I couldn't think of how to save a layer of information at first. Later I thought that I could press into a special object. Every time I got to this object, I knew it was a layer. I am using a null pointer, and I think this is a good fit. After a node enters the queue at a layer, it should be pushed into a NULL value. When all nodes at a layer are processed, a NULL value should be entered at the end of the queue, this is the demarcation line of the next layer.
Yesterday I saw another method in another question. Using a Data Structure vector <set <*> (2), of course, what struct is wrapped in the vector is not important, you only need to be able to quickly press in and access them sequentially. The dimension of vector is two-dimensional, which stores the objects of the current layer and the previous layer. Then, two mutex int values cur and pre are used to save the vector that is being accessed and the previous access. Each traversal scans the pre layer, and the discovered nodes are added to the cur layer. During the next loop, exchange.
I think this is a good idea, although it has been used in ordinary sequence traversal to kill chickens with a ox knife.
class Solution {public: int minDepth(TreeNode *root) { if(root == NULL) return 0; int res = 1; queue<TreeNode*> ceng; TreeNode *pNode; ceng.push(root); ceng.push(NULL); while(!ceng.empty()){ if(ceng.front() == NULL){ res++; ceng.pop(); ceng.push(NULL); } pNode = ceng.front(); ceng.pop(); if(!pNode->left&&!pNode->right) return res; if(pNode->left) ceng.push(pNode->left); if(pNode->right) ceng.push(pNode->right); } return res; }};