0
点赞
收藏
分享

微信扫一扫

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)
class Solution {

int res = 0;

public int maxDepth(TreeNode root) {
dfs(root, 1);
return res;
}

void dfs(TreeNode node, int l) {

if (node == null) {
return;
}

res = Math.max(res, l);

dfs(node.left, l + 1);
dfs(node.right, l + 1);
}
}

// 解决方案(2)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}

// 解决方案(3)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
List<TreeNode> queue = new LinkedList<>() {{ add(root); }}, tmp;
int res = 0;
while(!queue.isEmpty()) {
tmp = new LinkedList<>();
for(TreeNode node : queue) {
if(node.left != null) tmp.add(node.left);
if(node.right != null) tmp.add(node.right);
}
queue = tmp;
res++;
}
return res;
}
}
  • 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)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};

// 解决方案(2)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
vector<TreeNode*> que;
que.push_back(root);
int res = 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++;
}
return res;
}
};


举报

相关推荐

0 条评论