GATE CSE
First time here? Checkout the FAQ!
x
+3 votes
102 views

Consider the following code

asked in Programming by Veteran (54.8k points)   | 102 views
x is uninitialised..How to go about it..:)
x is no where used in the code. And the question asks for the sum of the internal nodes after the execution of that function. So i think ans is 22.
yes, x is not required in calculation . na?

@Habib

1 Answer

+5 votes
Best answer
It will change the value of all the nodes which are odd.

Means root->left  will become 0 from 1

and root->right will become 6 from 7

4  

0 6

6 4 2

8 2 8

Now sum of internal nodes wil be : 4 + 0 + 6 + 6 + 4 + 2 =  22
answered by Loyal (2.8k points)  
selected by
//check the code for the above , run it on ide , 
//and tested it yourself with different test cases.
#include <bits/stdc++.h>
using namespace std;
struct treenode{
 int data;
 treenode *left;
 treenode *right;
};
treenode* create(int data){
   treenode *temp = (treenode*)malloc(sizeof(treenode));
   temp->data = data;
   temp->left = temp->right  = NULL;
   return temp;
}
int solve(treenode *root) { // will return 0 always
  int x;
  if(root == NULL) return 0;
  else
  if(root->data % 2 == 1){ // changing odd data items
      root->data -= 1;
      x++;
  }
  return solve(root->left) + solve(root->right);
}
void inorder(treenode *root) {
  if(root == NULL) return;
    inorder(root->left);
    cout << root->data <<" ";
    inorder(root->right);
}
int main(){
     treenode *root;
     root = create(4);
     root->left = create(1);
     root->right = create(7);
     root->left->left = create(6);
     root->left->right = create(4);
     root->right->left = create(2);
     root->left->left->right = create(8);
     root->left->right->left = create(2);
     root->right->left->left = create(8);
     cout << solve(root) << endl;
     inorder(root);
     cout << endl;
    return 0;
}

 



// output
0
6 8 0 2 4 4 8 2 6 

 


 



Top Users Jun 2017
  1. Bikram

    3704 Points

  2. Hemant Parihar

    1484 Points

  3. junaid ahmad

    1432 Points

  4. Arnab Bhadra

    1408 Points

  5. Niraj Singh 2

    1311 Points

  6. Rupendra Choudhary

    1194 Points

  7. rahul sharma 5

    1132 Points

  8. Debashish Deka

    1004 Points

  9. srestha

    932 Points

  10. Arjun

    930 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 Jun 19 - 25
  1. Bikram

    1960 Points

  2. Niraj Singh 2

    1306 Points

  3. junaid ahmad

    502 Points

  4. sudsho

    410 Points

  5. akankshadewangan24

    388 Points


23,355 questions
30,066 answers
67,371 comments
28,382 users