Geeks LCA最低公共单亲节点
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Geeks LCA最低公共单亲节点相关的知识,希望对你有一定的参考价值。
给出一颗二叉树。找到两个值的最小公共节点。
假设两个值都会在树中出现。
假设可能不会出现的话,也非常easy。就查找一遍看两个值是否在树中就能够了。假设不在就直接返回NULL。
基本思想:就是在二叉树中比較节点值和两个值的大小,假设都在一边(左边或者右边)那么就往下继续查找,否则就是都在同一边了,那么就能够返回这个节点了,这个节点就是最低公共单亲节点了。
參考:http://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/
#include <stdio.h> #include <stdlib.h> class LCABST { struct Node { int data; Node *left, *right; Node(int d) : data(d), left(NULL), right(NULL) {} }; Node *lca(Node *root, int n1, int n2) { if (!root) return NULL; if (n1 < root->data && n2 < root->data) return lca(root->left, n1, n2); if (root->data < n1 && root->data < n2) return lca(root->right, n1, n2); return root; } Node *lcaIter(Node *root, int n1, int n2) { while (root) { if (n1 < root->data && n2 < root->data) root = root->left; else if (root->data < n1 && root->data < n2) root = root->right; else break; } return root; } Node *root; public: LCABST() { run(); } void run() { // Let us construct the BST shown in the above figure root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(4); root->left->right = new Node(12); root->left->right->left = new Node(10); root->left->right->right = new Node(14); int n1 = 10, n2 = 14; Node *t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 14, n2 = 8; t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 10, n2 = 22; t = lca(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 10, n2 = 14; printf("\nIterative Run:\n"); t = lcaIter(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 14, n2 = 8; t = lcaIter(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); n1 = 10, n2 = 22; t = lcaIter(root, n1, n2); printf("LCA of %d and %d is %d \n", n1, n2, t->data); } ~LCABST() { deleteTree(root); } void deleteTree(Node *r) { if (!r) return; deleteTree(r->left); deleteTree(r->right); delete r; r = NULL; } };
以上是关于Geeks LCA最低公共单亲节点的主要内容,如果未能解决你的问题,请参考以下文章