代码改变世界

Maximum Depth of Binary Tree

2015-04-11 10:58  笨笨的老兔子  阅读(112)  评论(0编辑  收藏  举报

求一棵树的最大深度

思路:广度优先搜索即可

  1. class Solution {
  2. public:
  3. int maxDepth(TreeNode *root) {
  4. int depth = 0;
  5. if (!root)
  6. return depth;
  7. queue<TreeNode*> nodeQue;
  8. nodeQue.push(root);
  9. while (!nodeQue.empty())
  10. {
  11. depth++;
  12. int qSize = nodeQue.size();
  13. for (size_t i = 0; i < qSize; i++)
  14. {
  15. if (nodeQue.front()->left)
  16. nodeQue.push(nodeQue.front()->left);
  17. if (nodeQue.front()->right)
  18. nodeQue.push(nodeQue.front()->right);
  19. nodeQue.pop();
  20. }
  21. }
  22. return depth;
  23. }
  24. };