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

bfs-dfs-bst

时间:2015-01-10 18:20:29      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:dfs   bfs   bst   

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

bfs :

void bfs(TreeNode *root)
{
	if(root==NULL)
		return;	
	queue<TreeNode *> x;
	TreeNode *t;
	x.push(root);
	while(!x.empty()){
		t = x.front();
		if(t->left!=NULL)
			x.push(t->left);
		if(t->right!=NULL)
			x.push(x->right);
		// do something
		x.pop();
	}
}
递归dfs:

void dfs(TreeNode *root)
{
	if(root==NULL)
		return;	
	if(root->left != NULL)
		dfs(root->left);
	if(root->right != NULL)
		dfs(root->right);
	// do something
}
迭代dfs, post_order traverse,稍微修改left,right顺序,就是previous_order traverse

void dfs(TreeNode *root)
{
	if(root==NULL)
		return;	
	stack<TreeNode *> x;
	unorder<TreeNode *,bool> m;
	x.push(root);
	while(!x.empty()){
		t = x.top();
		if(t->left != NULL && m[t->left] == 0)
			x.push(t->left);
		else if(t->right != NULL && m[t->right] == 0)
			x.push(t->right);
		else{
			// do something
			m[t] = 1;		
			x.pop();
		}
	}
}
递归inorder

void inorder(TreeNode *root)
{
	if(root==NULL)
		return;	
	if(root->left != NULL)
		inorder(root->left);
	// do something with root

	if(root->right != NULL)
		inorder(root->right);		
}
迭代inorder

void inorder(TreeNode *root)
{
	if(root==NULL)
		return;	
	stack<TreeNode *> x;
	unordered_map<TreeNode *,bool> m;
	TreeNode *t;
	x.push(back);
	
	while(!x.empty()){
		t = x.top();
		if(t->left != NULL && m[t->left] == 0){
			t = t-left;
			x.push(t);
		}
		else{
			x.pop();
			m[t] = 1;

			// do something

			if(t->right != NULL)
				x.push(t->right);	
		}
	}		
}


bfs-dfs-bst

标签:dfs   bfs   bst   

原文地址:http://blog.csdn.net/zcliatb/article/details/42583255

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