无法找出二叉树的高度

问题描述:

我无法得到正确的答案。无法找出二叉树的高度

int height(Node* root) { 
     // Write your code here. 
     if (root == NULL) 
     return 0; 

     // find the height of each subtree 
     int lh = height(root->left); 
     int rh = height(root->right); 

     return max(lh,rh)+1; 
} 
+2

你能给一个具体的例子失败并告诉我们你期望什么吗? – doctorlove

+1

你的逻辑看起来不错,但也许你有一个我没有看到的C特定错误。 –

+0

欢迎来到Stack Overflow!当问题陈述简单地说,“它不起作用”时,很难提供解决方案。请[编辑]您的问题,以更全面地描述您预期会发生什么以及与实际结果有何不同。看[问]提示什么是一个很好的解释。 –

我想你解决的问题是root被认为是在高度为0.这里是更新的解决方案。

int height(Node* root) { 
    if (root == NULL) return 0; 
    if (root ->left== NULL && root->right== NULL) 
    return 0; 

    // find the height of each subtree 
    int lh = height(root->left); 
    int rh = height(root->right); 

    return max(lh,rh)+1; 

    // Write your code here. 
}