crack the code interview 4.6

Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

#include

using namespace std;


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


bool cover(TreeNode * root, TreeNode * node);


int FindAncestor(TreeNode * root, TreeNode * node1, TreeNode * node2)
{
    if (cover(root->left, node1) && cover(root->left, node2))
        return FindAncestor(root->left, node1, node2);
    else if (cover(root->right, node1) && cover(root->right, node2))
        return FindAncestor(root->right, node1, node2);
    else
        return root->value;
}


bool cover(TreeNode * root, TreeNode * node)
{
    if (root == NULL)
        return false;
    if (root == node)
        return true;
    else
        return cover(root->left, node) | cover(root->right, node);
}


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


    cout<     return 0;
}

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