输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
广搜、一层一层数,以便计层数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution { public: int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) { return 0; } else { queue<TreeNode*> q; int depth = 0; int kids_finished = 0; int total_kids = 1; q.push(pRoot); while (q.size() > 0) { TreeNode* current = q.front(); q.pop(); kids_finished++; if (current->left != nullptr) { q.push(current->left); } if (current->right != nullptr) { q.push(current->right); } if (kids_finished == total_kids) { depth++; kids_finished = 0; total_kids = q.size(); } } return depth; } } };
|