Last active
October 9, 2017 08:59
-
-
Save tamarous/9e58340861b8b013cf537f1ae6bcfab8 to your computer and use it in GitHub Desktop.
二叉查找树-DFS与BFS的实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstddef> | |
#include <queue> | |
#include <string> | |
#include <cstdlib> | |
#include <stack> | |
using namespace std; | |
class Node { | |
public: | |
int data; | |
Node *left, *right; | |
Node(int d) { | |
data = d; | |
left = right = NULL; | |
} | |
}; | |
class Solution { | |
public: | |
Node* insert(Node* root, int data) { | |
if (root == NULL) { | |
return new Node(data); | |
} else { | |
Node* cur; | |
if (data <= root->data) { | |
cur = insert(root->left, data); | |
root->left = cur; | |
} else { | |
cur = insert(root->right, data); | |
root->right = cur; | |
} | |
return root; | |
} | |
} | |
void BFS(Node * root) { | |
//Write your code here | |
if (root != NULL) { | |
queue<Node *> q; | |
q.push(root); | |
Node *tree; | |
while (! q.empty()) | |
{ | |
tree = (Node *)q.front(); | |
q.pop(); | |
cout << tree->data << endl; | |
if (tree->right != NULL) { | |
q.push(tree->right); | |
} | |
if (tree->left != NULL) { | |
q.push(tree->left); | |
} | |
} | |
} | |
} | |
void DFS(Node *root) { | |
if (root != NULL) { | |
stack<Node *> stack; | |
stack.push(root); | |
Node *node; | |
while (!stack.empty()) { | |
node = stack.top(); | |
cout << node->data << endl; | |
stack.pop(); | |
if (node->right) { | |
stack.push(node->right); | |
} | |
if (node->left) { | |
stack.push(node->left); | |
} | |
} | |
} | |
} | |
};//End of Solution | |
int main() { | |
Solution myTree; | |
Node* root = NULL; | |
int T, data; | |
cin >> T; | |
while (T-- > 0) { | |
cin >> data; | |
root = myTree.insert(root, data); | |
} | |
cout << "BFS:" << endl; | |
myTree.BFS(root); | |
cout << "DFS:" << endl; | |
myTree.DFS(root); | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment