We were discussing tge predecessor and successor in a preorder traversal The Predecessor for a Binary Search Tree can be looked up in the following way:
Node GetPredecessor(Node root)
{
if (root == NULL) return root;
if (root.left )
{
Node current = root.left;
While (current && current.right)
Current = current.right;
Return current;
}
Node parent = GetParent(root);
While (parent && parent.left == root)
{
root = parent;
parent = GetParent(root, parent);
}
return parent;
}
Node GetParent(Node root, Node child)
{
If (child == null) return null;
Node parent = null;
While ( root )
{
If (child.val == root.val) return parent;
parent = root;
If (child.val < root.val)
Root = root.left;
Else
Root = root.right;
}
Return null;
}
Node TreeSuccessor(Node z)
(
if (z == null) return null;
if (z.right)
return TREE_MINIMUM(z.right);
Node parent = z.parent;
while(parent && parent.right == z)
{
z = parent;
parent = parent.parent;
}
return parent;
}
Node GetPredecessor(Node root)
{
if (root == NULL) return root;
if (root.left )
{
Node current = root.left;
While (current && current.right)
Current = current.right;
Return current;
}
Node parent = GetParent(root);
While (parent && parent.left == root)
{
root = parent;
parent = GetParent(root, parent);
}
return parent;
}
Node GetParent(Node root, Node child)
{
If (child == null) return null;
Node parent = null;
While ( root )
{
If (child.val == root.val) return parent;
parent = root;
If (child.val < root.val)
Root = root.left;
Else
Root = root.right;
}
Return null;
}
Node TreeSuccessor(Node z)
(
if (z == null) return null;
if (z.right)
return TREE_MINIMUM(z.right);
Node parent = z.parent;
while(parent && parent.right == z)
{
z = parent;
parent = parent.parent;
}
return parent;
}
No comments:
Post a Comment