二进制搜索树计数在C ++中返回错误的值

时间:2017-06-26 21:01:19

标签: c++ binary-search-tree

有人可以帮助新手试图在C ++中的二叉树上理解这些简单的递归函数吗?

函数sizeofTree继续返回NULL。

感谢您提供的任何帮助!

#include "stdafx.h"
#include <conio.h>

struct node {
    int val;
    struct node* pLeft;
    struct node* pRight;
};

struct node* newNode(int val) {
 struct node* node = new (struct node);
 node->val = val;
 node->pLeft = NULL;
 node->pRight = NULL;
 return(node);
}

struct node* insertNode(struct node* _node, int val) {
 if (_node == NULL) return (newNode(val));
    //if (val == _node->val) return NULL;  //error handling routine
 else if (val < _node->val) _node->pLeft = insertNode(_node->pLeft, val);
 else _node->pRight = insertNode(_node->pRight, val);
}

int sizeofTree(node* _node) {
 if (_node == NULL) {
  printf("For some reason, _node is evaluating to NULL.\n");  
  return(0);
 }
 else return(sizeofTree(_node->pLeft) + sizeofTree(_node->pRight));
}

int main() {
 node* root = newNode(2);
 root->pLeft = newNode(1);
 root->pRight = newNode(3);
 printf("root is: %d\n", root->val);
 printf("left leaf is: %d\n", root->pLeft->val);
 printf("right leaf is: %d\n", root->pRight->val);
 printf("The size of tree is: %d\n", sizeofTree(root));
 getch();
}

0 个答案:

没有答案