why are we returning root…?
plzz tell how the stack frame looks when we return a root here?
Build the tree using recursion
class node{
public:
int data;
nodeleft;
noderight;
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree(){
int d;
cin>>d;
if(d==-1){
return NULL;
}
node * root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
hey @ynikhil1999, we returning root because tree is identified by its root only. In future this root is passed to functions which want to make changes in the tree.
As root is local variable to build tree function, it will remain stack frame till return statement in build tree function encountered OR build tree function gets over.