BFS DFS(C++ )
阿新 • • 發佈:2018-12-13
BFS DFS(C++ )
/*
A
/ \
B C
/ \ / \
D E F G
深度優先遍歷(DFS) : A B D E C F G
廣度優先遍歷(BFS) : A B C D E F G
*/
TreeNode:
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };
//深度優先遍歷(DFS) void depthFirstSearch(TreeNode* root){ stack<TreeNode *> nodeStack; //使用C++的STL標準模板庫 nodeStack.push(root); TreeNode *node; while (!nodeStack.empty()){ node = nodeStack.top(); cout << node->val; nodeStack.pop(); if (node->right){ nodeStack.push(node->right); //先將右子樹壓棧 } if (node->left){ nodeStack.push(node->left); //再將左子樹壓棧 } } }
//DFS 遞迴實現
void dfs(TreeNode* root)
{
if (root){
cout << root->val;
dfs(root->left);
dfs(root->right);
}
}
//廣度優先遍歷(BFS) void breadthFirstSearch(TreeNode* root){ queue<TreeNode *> nodeQueue; //使用C++的STL標準模板庫 nodeQueue.push(root); TreeNode *node; while (!nodeQueue.empty()){ node = nodeQueue.front(); nodeQueue.pop(); cout << node->val; if (node->left){ nodeQueue.push(node->left); //先將左子樹入隊 } if (node->right){ nodeQueue.push(node->right); //再將右子樹入隊 } } }