【发布时间】:2020-03-22 12:16:33
【问题描述】:
我正在尝试查找二叉树的高度,这是我的尝试
#include<iostream>
#include<stack>
using namespace std;
int total = 0;
int length = -1;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int k){
data = k;
left = right = NULL;
}
};
void height(Node *root){
if(root==NULL)
return;
length++;
if(length>total)
total = length;
height(root->left);
height(root->right);
}
int main(){
Node *root = new Node(3);
root->left = new Node(4);
root->left->left = new Node(5);
root->right = new Node(6);
root->right->left = new Node(7);
height(root);
cout<<total;
return 0;
}
这里的length 和total 被声明为分别具有-1 和0 值的全局变量。 当我运行代码时,我得到的输出是树中的节点数 - 1,而不是树的高度。请在这里告诉我我的错误。
【问题讨论】:
-
请发布一个最小的工作代码,以便大家尝试。
-
@theWiseBro 我已经包含了相同的工作代码。请查看问题
标签: c++ recursion data-structures scope binary-tree