bfs-dfs-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顺序,就是其right-middle-left这种形式的访问。

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);	
		}
	}		
}

迭代preorder traverse

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.pop();
		mark[t] = true;

		// dosomething 

		if(t->left != NULL && m[t->left] == 0)
			x.push(t->left);
		if(t->right != NULL && m[t->right] == false)
			x.push(t->right);
	}		
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值