【问题标题】:recursive code for finding the height of a binary tree用于查找二叉树高度的递归代码
【发布时间】: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


【解决方案1】:

当然,您要在每个节点上增加 length

如果是递归的话,其实很简单:

std::size_t height(Node const *root) {
    if(!root) return 0;
    return 1 + std::max(height(root->left), height(root->right));
}

【讨论】:

    【解决方案2】:

    您的方法更多的是回溯,而不是简单的递归。在这种方法中,您应该注意在每一步都恢复到原始状态。这里length 总是在递增。您应该将其还原。

    void height(Node *root){
        if(root==NULL)
            return;
        length++;
        total = std::max(total,length+1); // Either this or initialize length as 0
        height(root->left);
        height(root->right);
        length--; // <--- Add this line
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-18
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多