0
点赞
收藏
分享

微信扫一扫

DFS和BFS

大明宫 2022-04-13 阅读 35
c++

在这里插入图片描述

#include<stack>
struct TreeNode
{
	int val = 0;
	TreeNode* left = nullptr;
	TreeNode* right = nullptr;
};

vector<int> dfs(TreeNode *root) {
	vector<int> res;
	stack<TreeNode*> _stack;
	_stack.push(root);
	while (!_stack.empty()) {
		TreeNode* treeNode = _stack.top();
		_stack.pop();
		// 遍历节点 
		res.push_back(treeNode->val);
			// 先压右节点 
		if (treeNode->right != nullptr) {
			_stack.push(treeNode->right);
		}

		// 再压左节点 
		if (treeNode->left != nullptr) {
			_stack.push(treeNode->left);
	}
	}
	return res;
}

int main()
{	
	TreeNode root, a, b,c,d;
	root.val = 1;
	root.left = &a;
	root.right = &b;
	b.val = 4;
	a.val = 2;
	a.left = &c;
	a.right = &d;
	c.val = 5;
	d.val = 6;
	vector<int> res = dfs(&root);
	for (auto x : res) {
		cout << x << endl;
	}


}
举报

相关推荐

bfs和dfs

BFS和DFS

python dfs和bfs

DFS和BFS简述

BFS/DFS

BFS搜索和DFS搜索

Pots(DFS &BFS)

0 条评论