码迷,mamicode.com
首页 > 其他好文 > 详细

Geeks LCA最低公共单亲节点

时间:2017-07-09 13:57:48      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:查找   out   mon   const   arc   www   str   struct   nod   

给出一颗二叉树。找到两个值的最小公共节点。

假设两个值都会在树中出现。

假设可能不会出现的话,也非常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最低公共单亲节点

标签:查找   out   mon   const   arc   www   str   struct   nod   

原文地址:http://www.cnblogs.com/tlnshuju/p/7141111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!