Monday, April 21, 2014

Find the "next" node in a in-order traversal of a given node

Since it is in-order traversal, the next node is the node with the next big value.
There are many cases to think about. But in all, it comes only two cases.
1. If the given node has right child, the next node is the left most child node of that right child.
2. If the given node has no right child, the next node is its upper parent where this node is reside in its left subtree. That is, go all the way up to find the first node whose left subtree has this node.

Code:
TreeNode* leftMostChild(TreeNode* node)
{
    if (!node) return nullptr;
    while(node->left)
    {
        node = node->left;
    }
    return node;
}

TreeNode* inorderSucc(TreeNode* node)
{
    if (!node) return nullptr;
    if (node->right)
    {
        return leftMostChild(node->right);
    }
    else
    {
        TreeNode* q = node;
        TreeNode* x = q->parent;

        while(x && x->left!=q )
        {
            q = x;
            x = x->parent;
        }
        return x;
    }
}

No comments:

Post a Comment