如何求树中的两个节点的最近公共祖先?

来源:互联网 发布:汽车保险算法 编辑:程序博客网 时间:2024/05/18 18:44

如何求树中的两个节点的最近公共祖先?

看到别人的一个比较好的写法如下,大多数人的写法是把父节点存入数组,然后遍历父节点数组寻找最后一个相同节点

或者用含有指向父节点指针的树结构,向上遍历父节点找第一个相同节点为最近祖先节点

struct Node{int data;Node* left;Node* right;};int fun(Node* root,Node* ptr1,Node* ptr2,Node** out){if(root==NULL)return 0;if(root==ptr1||root==ptr2)return 1;int leftint=0,rightint=0;leftint= fun(root->left,ptr1,ptr2,out);if(leftint==2)return 2;rightint=fun(root->right,ptr1,ptr2,out);if(rightint==2)return 2;}if(leftint+rightint==2)*out=root;return leftint+rightint;}int main(){Node* root=...;Node* ptr1=...;Node* ptr2=...;Node* out;int n=fun(root,ptr1,ptr2,&out);if(n==2)cout<<"result node is: "out->data<<endl;elsecout<<"Node not exist...";return 0;}


原创粉丝点击