Binary tree problems

* Binary tree的资料~ http://cslibrary.stanford.edu/110/BinaryTrees.html

1. Print binary tree in level order

class Node{
public:
	Node(int v)
	{
		value = v;
		left = 0;
		right = 0;
	}
	int value;
	Node *left;
	Node *right;
};
//Print binary tree in level order
void BST::bfs(Node *p)
{
	queue<Node *> q;
	q.push(p);
	q.push(0);
	while(q.front() != 0)
	{
		Node *cur = q.front();
		while(cur != 0)
		{
			cout<<cur->value<<" ";
			if(cur->left != 0)
				q.push(cur->left);
			if(cur->right != 0)
				q.push(cur->right);
			q.pop();
			cur = q.front();
		}
		q.pop();
		q.push(0);
		cout<<endl;
	}
}

 

//Implement by two queues. q1 stores the nodes of next level, 
//and q2 stores the current level.

void BST::printLevelOrder2q(Node *p)
{
	queue<Node *> q1;
	queue<Node *> q2;

	cout<<p->value<<endl;
	q1.push(p->left);
	q1.push(p->right);

	while(!(q2.empty() && q1.empty()))
	{
		while(!q1.empty())
		{
			q2.push(q1.front());
			q1.pop();
		}
		while(!q2.empty())
		{
			Node *curr = q2.front();
			cout<<curr->value<<" ";
			if(q2.front()->left != 0)
				q1.push(curr->left);
			if(q2.front()->right != 0)
				q1.push(curr->right);
			q2.pop();
		}
		cout<<endl;
	}
}

 

2. Determine if a binary tree is a Binary search tree (BST).

bool isBST(bsNode *p)
{
	static int prev = 0;

	if(!p)
		return true;

	if(isBST(p->left))
	{
		if(prev <= p->value)
		{
			prev = p->value;
			return isBST(p->right);
		}
		else
			return false;
	}
	else
		return false;
}

3. Height of a binary tree.

 

int BST::depth(Node *root)
{
	if(root == 0)
		return 0;
	else
	{
		int rDepth = depth(root->right);
		int lDepth = depth(root->left);
		return 1 + (rDepth>lDepth ? rDepth : lDepth);
	}
}

 

4. Find kth smallest elment in a BST

Dd inorder traversal and counting the number of reached element, when the counter catch the k then return that element.

 

int BST::kMin(Node *p, int k)
{
	static int count = 0;

	if(p != 0)
	{
		kMin(p->left,k);
		++count;
		if(count == k)
		{
			return p->value;
		}
		kMin(p->right,k);
	}
}

 

5. Binary tree is symmetrical. 

bool IsMirror(Node * rootA, Node * rootB)
{
	if ( rootA == 0 && rootB == 0 )
		return true;
	
	if ( rootA == 0 || rootB == 0)
		return false;

	return rootA->Value == rootB->Value
		&& IsMirror(rootA->Left, rootB->Right)
		&& IsMirror(rootA->Right, rootB->Left);
}

bool IsMirror(Node * root)
{
	return IsMirror(root->Left, root->Right);
}

  

6. Lowest Common Ancestor

 

Node* BST::LCA(Node *root, Node *p, Node *q)
{
	if(!root || !p || !q)
		return 0;

	if(max(p->value ,q->value) < root->value)
		return LCA(root->left, p, q);
	else if(min(p->value, q->value) > root->value)
		return LCA(root->right, p, q);
	else
		return root;
}

  

posted @ 2011-08-05 12:21  Sw_R  阅读(163)  评论(0编辑  收藏  举报