#include<iostream>
#include<sstream>
#include<string>
#include<queue>
using namespace std;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
queue<TreeNode*> q;
q.push(root);
//root本身就是一层,将depth初始化为1
int depth = 1;
while (!q.empty()) {
int sz = q.size();
//将当前队列中的所有节点向四周扩散
for (int i = 0; i < sz; i++) {
TreeNode* node = q.front();
q.pop();
//判断是否到达终点
if (node->left == NULL && node->right == NULL) return depth;
//将node的相邻节点加入队列
if (node->left != NULL) q.push(node->left);
if (node->right != NULL) q.push(node->right);
}
//在这里增加步数
depth++;
}
return depth;
}
};
void trimLeftTrailingSpaces(string& input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string& input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
TreeNode* stringToTreeNode(string input) {
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
if (!input.size()) {
return nullptr;
}
string item;
stringstream ss;
ss.str(input);
getline(ss, item, ',');
TreeNode* root = new TreeNode(stoi(item));
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
while (true) {
TreeNode* node = nodeQueue.front();
nodeQueue.pop();
if (!getline(ss, item, ',')) {
break;
}
trimLeftTrailingSpaces(item);
if (item != "null") {
int leftNumber = stoi(item);
node->left = new TreeNode(leftNumber);
nodeQueue.push(node->left);
}
if (!getline(ss, item, ',')) {
break;
}
trimLeftTrailingSpaces(item);
if (item != "null") {
int rightNumber = stoi(item);
node->right = new TreeNode(rightNumber);
nodeQueue.push(node->right);
}
}
return root;
}
int main() {
string line;
while (getline(cin, line)) {
TreeNode* root = stringToTreeNode(line);
int ret = Solution().minDepth(root);
string out = to_string(ret);
cout << out << endl;
}
return 0;
}
06-23
859
01-28
999
03-22
1974
10-14
1599