解法:
#include<iostream>
#include<queue>
using namespace std;
// 定义二叉树结点
struct TreeNode {char val;TreeNode* left;TreeNode* right;TreeNode(char x) :val(x), left(NULL), right(NULL) {};
};
// 先序递归遍历建立二叉树
TreeNode* buildTree() {char c;cin >> c;if (c == '#') {return NULL;}TreeNode* root = new TreeNode(c);root->left = buildTree();root->right = buildTree();return root;
}
int getDepth(TreeNode* root) {int result = 0;queue<TreeNode*> q;q.push(root);while (!q.empty()) {int num = q.size();result = max(result, num);for (int i = 0; i < num; i++) {TreeNode* cur = q.front();q.pop();if (cur->left) q.push(cur->left);if (cur->right) q.push(cur->right);}}return result;
}
int main() {TreeNode* root= buildTree();cout<<getDepth(root);return 0;
}