Given a node, find inorder traversal next.
The most straightforward idea is that inorder traverses the entire BST and then looks in the results of the traversal. But it takes extra space and time.
Geeksforgeek
(1) with parent pointer
I have a good explanation on the cc150.
Three types of cases:
I current node right! = NULL, then return leftmost of right subtree
II current node.right = = NULL
If node is the left child of its parent, you can return directly to the Node.parent
If node is the parent right child, continue up until node is in parent left subtree
Node INORDERSUCC (node N) {if (n have a right subtree) {return leftmost child of right Subtree}else{while (n was a right child of N.parent) {n = n.parent;//Go Up}return n.parent; Parent has not been traversed}}
Actual code:
1 Public StaticTreeNode Inordernext (TreeNode node) {2 if(node = =NULL)return NULL;3 4 if(N.parent = =NULL|| node.right!=NULL){5 returnLeftmostchild (node.right);6}Else{7 8TreeNode cur =node;9TreeNode parent =cur.parent; Ten //Go up until we ' re on left instead in right One A while(Parent! =NULL&& Parent.left! =cur) { -Cur =parent; -Parent =parent.parent; the } - returnparent; - } - } + Public StaticTreeNode Leftmostchild (TreeNode N) { - if(n = =NULL) { + return NULL; A } at while(n.left!=NULL){ -n =N.left; - } - returnN; -}View Code
(2) No parent pointer http://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/
In fact, the only difference is to find the parent or gradparent part, at this time we need to wait until the root of this tree, from the top down, record the parent
1 PublicTreeNode Findsuccssor (TreeNode node, TreeNode root) {2 3 if(Node.right! =NULL){4 returnLeftmostchild (node.right);5 }6TreeNode SUCC =NULL;7 //need to start from root, and search for successor the tree8 while(Root! =NULL){9 if(Root.val <node.val) {Ten //node if on right subtree One ARoot =Root.right; -}Else if(Root.val >node.val) { - //node is on the left subtree theSUCC =Root; -Root =Root.left; -}Else{ - //Root.val = = Node.val; + Break; - } + } A at returnsucc; -}View Code
Find Next node in BST