crack the code interview 4.5

Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.

#include

using namespace std;


struct TreeNode
{
    int value;
    TreeNode * left;
    TreeNode * right;
    TreeNode * parent;
    TreeNode(int v)
    {
        value = v;
        left = NULL;
        right = NULL;
        parent = NULL;
    }
    TreeNode(int v, TreeNode * l, TreeNode * r)
    {
        value = v;
        left = l;
        right = r;
    }
};


int FindNext(TreeNode * node)
{
    
    TreeNode * next = node;
    if (node->right != NULL)
    {
        next = node->right;
        while (next != NULL)
        {
            next = next->left;
        }
    }
    else
    {
        if (node->parent->left == node)
        {
            next = node->parent;
        }
        else if (node->parent->right == node)
        {
            if (node->parent->parent != NULL)
                next = node->parent->parent;
            else
                next = NULL;
        }
    }


    if (next != NULL)
        return next->value;
    else
    {
        cout<<"no next"<         return 0;
    }
}


int main()
{
    TreeNode * node0 = new TreeNode(0);
    TreeNode * node1 = new TreeNode(1);
    TreeNode * node2 = new TreeNode(2, node0, node1);
    node0->parent = node2;
    node1->parent = node2;
    TreeNode * node3 = new TreeNode(3);
    TreeNode * node4 = new TreeNode(4, node2, node3);
    node2->parent = node4;
    node3->parent = node4;


    cout<     return 0;
}

你可能感兴趣的:(crack,the,code,interview)