/* * @lc app=leetcode id=104 lang=javascript * * [104] Maximum Depth of Binary Tree *//** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param{TreeNode} root * @return{number} */varmaxDepth=function (root) {if (!root) return0;if (!root.left &&!root.right) return1;// 层次遍历 BFSlet cur = root;constqueue= [root,null];let depth =1;while ((cur =queue.shift()) !==undefined) {if (cur ===null) {// 注意⚠️: 不处理会无限循环,进而堆栈溢出if (queue.length===0) return depth; depth++;queue.push(null);continue; }constl=cur.left;constr=cur.right;if (l) queue.push(l);if (r) queue.push(r); }return depth;};
C++ Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
auto q = vector<TreeNode*>();
auto d = 0;
q.push_back(root);
while (!q.empty())
{
++d;
auto sz = q.size();
for (auto i = 0; i < sz; ++i)
{
auto t = q.front();
q.erase(q.begin());
if (t->left != nullptr) q.push_back(t->left);
if (t->right != nullptr) q.push_back(t->right);
}
}
return d;
}
};
Java Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicintmaxDepth(TreeNode root) {if(root ==null) {return0; }// 队列Queue<TreeNode> queue =newLinkedList<TreeNode>();queue.offer(root);int res =0;// 按层扩展while(!queue.isEmpty()) {// 拿出该层所有节点,并压入子节点int size =queue.size();while(size >0) {TreeNode node =queue.poll();if(node.left!=null) {queue.offer(node.left); }if(node.right!=null) {queue.offer(node.right); } size-=1; }// 统计层数 res +=1; }return res; }}