[面试] 二叉树两结点的最低共同父结点

题目:二叉树的结点定义如下:

struct TreeNode

{

    int m_nvalue;

    TreeNode* m_pLeft;

    TreeNode* m_pRight;

};

输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。

递归版本:空间O(1),时间O(n)

 

 1 struct Node
 2 {
 3     int val;
 4     Node *left;
 5     Node *right;
 6     Node():left(NULL), right(NULL){}
 7 };
 8 
 9 Node *findFather(Node *root, Node *node1, Node *node2, bool &node1Find, bool &node2Find)
10 {
11     if (root == NULL)
12         return NULL;
13 
14     bool leftNode1Find = false, leftNode2Find = false;
15     Node *leftNode = findFather(root->left, node1, node2, leftNode1Find, leftNode2Find);
16     if (leftNode != NULL)
17         return leftNode;
18 
19     bool rightNode1Find = false, rightNode2Find = false;
20     Node *rightNode = findFather(root->right, node1, node2, rightNode1Find, rightNode2Find);
21     if (rightNode != NULL)
22         return rightNode;
23 
24     node1Find = leftNode1Find || rightNode1Find;
25     node2Find = leftNode2Find || rightNode2Find;
26 
27     if (node1Find && node2Find)
28         return root;
29 
30     if (root == node1)
31         node1Find = true;
32 
33     if (root == node2)
34         node2Find = true;
35 
36     return NULL;
37 }

 

 

 

posted @ 2012-11-26 12:01  chkkch  阅读(1202)  评论(0编辑  收藏  举报