二叉树的最近公共祖先

 1 #include <stdio.h>
 2 
 3 typedef int ElementType;
 4 
 5 struct BinarySearchTreeNode
 6 {
 7     ElementType Element;
 8     struct BinarySearchTreeNode *Left;
 9     struct BinarySearchTreeNode *Right;
10 };
11 
12 //be careful with the names of the node and struct
13 struct BinarySearchTreeNode* BinaryTreeLCA(struct BinarySearchTreeNode* TreeRoot,struct BinarySearchTreeNode* TreeNode_1,struct BinarySearchTreeNode* TreeNode_2)
14 {
15     if(TreeRoot==NULL || TreeRoot==TreeNode_1 || TreeRoot==TreeNode_2)
16     {
17         return TreeRoot;
18     }
19     
20     struct BinarySearchTreeNode* NewLeft = BinaryTreeLCA(TreeRoot -> Left,TreeNode_1,TreeNode_2);
21     struct BinarySearchTreeNode* NewRight = BinaryTreeLCA(TreeRoot -> Right,TreeNode_1,TreeNode_2);
22     
23     if(NewLeft && NewRight)
24     {
25         return TreeRoot;
26     }
27     
28     return NewLeft == NULL ? NewRight : NewLeft;
29 }
30 
31 int main()
32 {
33     //struct BinarySearchTreeNode *TreeNode_1;
34     //struct BinarySearchTreeNode *TreeNode_2;
35     //struct BinarySearchTreeNode *TreeNodeLCA;
36     //TreeNode_1 = BinarySearchTreeNodeFind(2,TreeRoot);
37     //TreeNode_2 = BinarySearchTreeNodeFind(-1,TreeRoot);
38     //TreeNodeLCA = BinaryTreeLCA(TreeRoot,TreeNode_1,TreeNode_2);
39     return 0;
40 }

 

posted @ 2018-08-05 21:54  Asurudo  阅读(203)  评论(0编辑  收藏  举报