给定一个二叉树,编写一个函数来获取其最大深度。Java代码
时间: 2024-05-06 12:16:53 浏览: 17
下面是Java代码实现:
```
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
```
其中 `TreeNode` 是二叉树节点的定义,包含左右子节点和节点值:
```
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
```
这个算法的思路是递归地计算左子树和右子树的最大深度,然后返回两者中较大的深度加一。当根节点为空时,深度为零。
相关问题
编写函数,计算一棵给定二叉树的所有结点个数
好的,以下是计算一棵给定二叉树的所有结点个数的 Python 代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_nodes(root: TreeNode) -> int:
if not root:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
```
其中,`TreeNode` 是二叉树的结点类,包括 `val` 表示结点值,`left` 表示左子树,`right` 表示右子树。
函数 `count_nodes` 是计算二叉树结点个数的函数,采用递归的方式实现。如果当前结点为空,返回 0。否则,返回 1(表示当前结点)加上左子树的结点个数和右子树的结点个数。
编写函数,计算一棵给定二叉树的所有结点个数c++
好的,以下是计算一棵给定二叉树的所有结点个数的 C++ 代码:
```cpp
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int countNodes(TreeNode* root) {
if (!root) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
```
其中,`TreeNode` 是二叉树的结点类,包括 `val` 表示结点值,`left` 表示左子树,`right` 表示右子树。
函数 `countNodes` 是计算二叉树结点个数的函数,采用递归的方式实现。如果当前结点为空,返回 0。否则,返回 1(表示当前结点)加上左子树的结点个数和右子树的结点个数。