题目链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/
题目内容:
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.
题目分析:
一看到这道题,感觉如果用递归的方式解是否就会超时(男人的直觉告诉我!),但是有办法总比没有的好。于是开始码字:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
else {
if(maxDepth(root->left) > maxDepth(root->right)
return maxDepth(root->left) + 1;
else
return maxDepth(root->right) + 1;
}
}
三下五除二,啪啪啪提交之,结局我早已看到,TLE超时了。正当自己得意早已看穿一切的时候,觉得上面的写法有点点傻,为什么maxDepth(root->left)或者另一边要调用两次呢?没什么必要,可以赋值给变量以供后面用。这也是后来在leetCode上写代码时候的风格,赋值给变量能比重复调用运算符或者函数更节省时间。
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
else {
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left>right?left+1:right+1;
}
}
运行一下,AC了,而且效果貌似还行,跟大多数人一样8ms,花费的时候比较少比较靠前。不过说了,这种递归的肯定不如迭代的运行的省时,于是去讨论区看了一下其他人的解法(发现用递归的时候大家的思路基本没差到哪里去),有同志使用了Java栈和队列分别实现dfs和bfs,而且据称分别是7ms和3ms,下面借用之展示展示,不收广告费,如有侵犯,请联系我,必删之。
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> value = new Stack<>();
stack.push(root);
value.push(1);
int max = 0;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
int temp = value.pop();
max = Math.max(temp, max);
if(node.left != null) {
stack.push(node.left);
value.push(temp+1);
}
if(node.right != null) {
stack.push(node.right);
value.push(temp+1);
}
}
return max;
}
// 7ms
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int count = 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);
}
}
count++;
}
return count;
}
// 3ms