This can be done in O (n). That is, we visit each node of the tree only once. The logic is as follows. Maintain two variables on the left and on the right and initialize them to zero. When is there ever a recursive call to increment the left side to the left by 1 When is there ever a recursive call to increase the increment of the side to the left by 1
Starting with root, do a roundup in order and check if it is equal to right , which means we never made a recursive call to the right. If yes, type node, that means we print all the left nodes of the tree. If right is not equal to zero, they are not considered borders, so find the nodes of the sheet and print them.
Bypassing Inorder, after the left subtree calls are completed, you go to the root, and then the recursive call for the right under the tree. Now first check that the nodes of the leaves are cleaned and printed, and then check to see if it is left , which means that we made a recursive call on the left, so they are not considered a border. If the left has a zero print node, this means that we print all the rightmost nodes of the tree.
Code snippet
void btree::cirn(struct node * root,int left,int right) { if(root == NULL) return; if(root) { if(right==0) { cout<<root->key_value<<endl; } cirn(root->left,left+1,right); if(root->left==NULL && root->right==NULL && right>0) { cout<<root->key_value<<endl; } cirn(root->right,left,right+1); if(left==0) { if(right!=0) { cout<<root->key_value<<endl; } } }
}
source share