leetcode--Maximum Depth of Binary Tree
2017-05-02 21:12
429 查看
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question.
解题思路:
从根节点root开始,若为NULL则树的深度为0.
若root不为NULL,建立一个队列,放入root,开始循环.
计数自增1(count++),遍历整个队列,每检查一个元素;
若该元素的左节点不为NULL,则将该左节点放入队列;
若该元素的右节点不为NULL,则将该右节点放入队列;
从队列中删除该元素,若队列为空,退出循环
返回计数count
代码:
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question.
解题思路:
从根节点root开始,若为NULL则树的深度为0.
若root不为NULL,建立一个队列,放入root,开始循环.
计数自增1(count++),遍历整个队列,每检查一个元素;
若该元素的左节点不为NULL,则将该左节点放入队列;
若该元素的右节点不为NULL,则将该右节点放入队列;
从队列中删除该元素,若队列为空,退出循环
返回计数count
代码:
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int count= 0; queue<TreeNode *> q; q.push(root); while(!q.empty()) { count++; for(int i = 0, n = q.size(); i < n; ++ i) { TreeNode *p = q.front(); q.pop(); if(p -> left != NULL) q.push(p -> left); if(p -> right != NULL) q.push(p -> right); } } return count; } };
相关文章推荐
- [Leetcode 8] 104 Maximum Depth of Binary Tree
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- LeetCode_Maximum Depth of Binary Tree
- LeetCode题目笔记(二) -- Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- [leetcode刷题系列]Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree