标签:class blog code http ext com
给出一颗二叉树,找到两个值的最小公共节点。
假设两个值都会在树中出现。如果可能不会出现的话,也很简单,就查找一遍看两个值是否在树中就可以了。如果不在就直接返回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最低公共单亲节点,布布扣,bubuko.com
标签:class blog code http ext com
原文地址:http://blog.csdn.net/kenden23/article/details/31345677