Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Print Inorder successor in binary tree

Given a binary tree, print inorder successor of all binary tree nodes. we are solve this problem easily using recursion. First understand what is inorder successor of BST nodes.

For example

182105367

In this tree have 8 nodes. inorder traversal of this binary tree is [7,5,6,3,1,8,2,10]. Inorder traversal right side node is successor of pervious nodes.

View nodes of this tree.

Stack Areamainauxilary(pointer) NULLroot(pointer) Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 5left (pointer) right (pointer) struct Treedata (int)= 8left (pointer)= NULLright (pointer) struct Treedata (int)= 2left (pointer)= NULLright (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 3left (pointer) right (pointer)= NULLstruct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULL

View process to print tree nodes.

Stack Areamainauxilary(pointer)root(pointer)successorhead(pointer)last(pointer)successorhead(pointer)last(pointer)successorhead(pointer)last(pointer)successorhead(pointer)last(pointer)successorhead(pointer) NULLlast(pointer) Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 5left (pointer) right (pointer) struct Treedata (int)= 8left (pointer)= NULLright (pointer) struct Treedata (int)= 2left (pointer)= NULLright (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 3left (pointer) right (pointer)= NULLstruct Treedata (int)= 6left (pointer)= NULLright (pointer)= NULL

Visualize process Try it Yourself

Program to print inorder successor of given binary tree. Time complexity O(n).


Output

Submit your solution in comment.

Spread the post

Recommended Posts: