c - distance from root to a node of a binary tree -
i have find distance of node of binary tree root. solution is:
int distanceutil(struct node* root, int x, int dist) { if (root == null) { return -1; } else { if (root->data == x) { return dist; } return distanceutil(root->left, x, dist + 1) || distanceutil(root->right, x, dist + 1); } } int distance(struct node* root, int x) { return distanceutil(root, x, 0); } but not work.in fact when in main do:
struct node* root = newnode(12); root->left = newnode(8); root->right = newnode(18); root->left->left = newnode(2); root->left->right = newnode(9); root->right->left = newnode(15); root->right->right = newnode(22); root->right->right->right = newnode(33); printf("il cammino : %d", distance(root,33)); getchar(); return 0; it returns 1, should return 3. can me? thank's.
you're using logical or operator || combine results of searching left tree , right tree. results of operator 0 or 1, won't result besides that.
what want return larger of 2 values of each subtree search. store result of searching each side, check larger , return that.
int distanceutil(struct node* root, int x, int dist) { if (root == null) { return -1; } if (root->data == x) { return dist; } int left = distanceutil(root->left, x, dist + 1); int right = distanceutil(root->right, x, dist + 1); if (left > right) { return left; } else { return right; } }
Comments
Post a Comment