LeetCode(算法)- 104. 二叉树的最大深度

简介: LeetCode(算法)- 104. 二叉树的最大深度

题目链接:点击打开链接

题目大意:

解题思路:

相关企业

  • 领英(LinkedIn)
  • 字节跳动
  • Facebook
  • 亚马逊(Amazon)
  • 谷歌(Google)
  • 微软(Microsoft)
  • 彭博(Bloomberg)
  • 苹果(Apple)

AC 代码

  • Java
/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/// 解决方案(1)classSolution {
intres=0;
publicintmaxDepth(TreeNoderoot) {
dfs(root, 1);
returnres;
    }
voiddfs(TreeNodenode, intl) {
if (node==null) {
return;
        }
res=Math.max(res, l);
dfs(node.left, l+1);
dfs(node.right, l+1);
    }
}
// 解决方案(2)classSolution {
publicintmaxDepth(TreeNoderoot) {
if(root==null) return0;
returnMath.max(maxDepth(root.left), maxDepth(root.right)) +1;
    }
}
// 解决方案(3)classSolution {
publicintmaxDepth(TreeNoderoot) {
if(root==null) return0;
List<TreeNode>queue=newLinkedList<>() {{ add(root); }}, tmp;
intres=0;
while(!queue.isEmpty()) {
tmp=newLinkedList<>();
for(TreeNodenode : queue) {
if(node.left!=null) tmp.add(node.left);
if(node.right!=null) tmp.add(node.right);
            }
queue=tmp;
res++;
        }
returnres;
    }
}
  • C++
/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/// 解决方案(1)classSolution {
public:
intmaxDepth(TreeNode*root) {
if(root==nullptr) return0;
returnmax(maxDepth(root->left), maxDepth(root->right)) +1;
    }
};
// 解决方案(2)classSolution {
public:
intmaxDepth(TreeNode*root) {
if(root==nullptr) return0;
vector<TreeNode*>que;
que.push_back(root);
intres=0;
while(!que.empty()) {
vector<TreeNode*>tmp;
for(TreeNode*node : que) {
if(node->left!=nullptr) tmp.push_back(node->left);
if(node->right!=nullptr) tmp.push_back(node->right);
            }
que=tmp;
res++;
        }
returnres;
    }
};
目录
相关文章
|
6天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
12 0
|
6天前
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
8 0
|
6天前
leetcode代码记录(二叉树的最小深度
leetcode代码记录(二叉树的最小深度
10 0
|
6天前
leetcode代码记录(二叉树的最大深度
leetcode代码记录(二叉树的最大深度
9 0
|
6天前
leetcode代码记录(翻转二叉树
leetcode代码记录(翻转二叉树
8 0
|
6天前
leetcode代码记录(二叉树的层序遍历
leetcode代码记录(二叉树的层序遍历
12 0
|
6天前
|
算法
leetcode代码记录(二叉树递归遍历
leetcode代码记录(二叉树递归遍历
8 0
|
6天前
|
存储 算法
Leetcode 30天高效刷数据结构和算法 Day1 两数之和 —— 无序数组
给定一个无序整数数组和目标值,找出数组中和为目标值的两个数的下标。要求不重复且可按任意顺序返回。示例:输入nums = [2,7,11,15], target = 9,输出[0,1]。暴力解法时间复杂度O(n²),优化解法利用哈希表实现,时间复杂度O(n)。
22 0
|
6天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
6天前
|
算法
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
24 3