error: expression cannot be used as a function int rheight = r.height();
时间: 2024-05-21 15:11:28 浏览: 25
This error occurs when you try to use a class member function as if it were a regular function. In this case, it looks like you are trying to call a member function named "height()" on an object named "r", but you are using parentheses like you would with a regular function call.
To fix this error, you need to remove the parentheses and use the member function syntax to call the "height" function on the "r" object, like this:
int rheight = r.height;
相关问题
用Java实现分层二叉树
分层二叉树是一种特殊的二叉树,每层节点数都是2的幂次方。以下是用Java实现分层二叉树的代码:
```java
class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class LayeredBinaryTree {
Node root;
public LayeredBinaryTree() {
root = null;
}
public void insert(int val) {
if (root == null) {
root = new Node(val);
return;
}
Node curr = root;
while (curr.left != null && curr.right != null) {
if (val <= curr.val) {
curr = curr.left;
} else {
curr = curr.right;
}
}
if (val <= curr.val) {
curr.left = new Node(val);
} else {
curr.right = new Node(val);
}
}
public void printLevelOrder() {
int h = height(root);
for (int i = 1; i <= h; i++) {
printLevel(root, i);
System.out.println();
}
}
public int height(Node node) {
if (node == null) {
return 0;
} else {
int lheight = height(node.left);
int rheight = height(node.right);
return Math.max(lheight, rheight) + 1;
}
}
public void printLevel(Node node, int level) {
if (node == null) {
return;
}
if (level == 1) {
System.out.print(node.val + " ");
} else if (level > 1) {
printLevel(node.left, level - 1);
printLevel(node.right, level - 1);
}
}
}
```
这里定义了一个Node类和LayeredBinaryTree类,Node类表示树中的节点,LayeredBinaryTree类表示分层二叉树。insert方法用于插入节点,printLevelOrder方法用于按层遍历并打印分层二叉树,height方法用于计算分层二叉树的高度,printLevel方法用于打印某一层的节点。
18923 二叉树的直径
二叉树的直径是指任意两个节点间最长路径的长度。可以使用递归的思想来解决这个问题,具体的做法是:
1. 对于当前节点,计算经过该节点的最长路径长度,即左子树高度+右子树高度。
2. 分别递归左右子树,得到左右子树的最长路径长度。
3. 取三者中的最大值作为当前节点的最长路径长度。
4. 递归处理所有节点,计算出直径。
下面是基于上述思路的 C++ 代码实现:
```c++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
int lHeight = height(root->left);
int rHeight = height(root->right);
int lDiameter = diameterOfBinaryTree(root->left);
int rDiameter = diameterOfBinaryTree(root->right);
return max(lHeight + rHeight, max(lDiameter, rDiameter));
}
int height(TreeNode* node) {
if (!node) return 0;
return 1 + max(height(node->left), height(node->right));
}
```
其中,diameterOfBinaryTree 函数用于计算二叉树的直径,height 函数用于计算二叉树的高度。