600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 二叉树C++ | 深度优先遍历(前序 中序 后序)_3

二叉树C++ | 深度优先遍历(前序 中序 后序)_3

时间:2024-06-28 00:46:56

相关推荐

二叉树C++ | 深度优先遍历(前序 中序 后序)_3

深度优先遍历

/* Binary Tree Traversal - Preorder, Inorder, Postorder */#include<iostream>using namespace std;struct Node {char data;struct Node *left;struct Node *right;};//Function to visit nodes in Preordervoid Preorder(struct Node *root) {// base condition for recursion// if tree/sub-tree is empty, return and exitif(root == NULL) return;printf("%c ",root->data); // Print dataPreorder(root->left);// Visit left subtreePreorder(root->right); // Visit right subtree}//Function to visit nodes in Inordervoid Inorder(Node *root) {if(root == NULL) return;Inorder(root->left); //Visit left subtreeprintf("%c ",root->data); //Print dataInorder(root->right);// Visit right subtree}//Function to visit nodes in Postordervoid Postorder(Node *root) {if(root == NULL) return;Postorder(root->left); // Visit left subtreePostorder(root->right); // Visit right subtreeprintf("%c ",root->data); // Print data}// Function to Insert Node in a Binary Search TreeNode* Insert(Node *root,char data) {if(root == NULL) {root = new Node();root->data = data;root->left = root->right = NULL;}else if(data <= root->data)root->left = Insert(root->left,data);else root->right = Insert(root->right,data);return root;}int main() {/*Code To Test the logicCreating an example treeM/ \B Q/ \ \A C Z*/Node* root = NULL;root = Insert(root,'M'); root = Insert(root,'B');root = Insert(root,'Q'); root = Insert(root,'Z'); root = Insert(root,'A'); root = Insert(root,'C');//Print Nodes in Preorder. cout<<"Preorder: ";Preorder(root);cout<<"\n";//Print Nodes in Inordercout<<"Inorder: ";Inorder(root);cout<<"\n";//Print Nodes in Postordercout<<"Postorder: ";Postorder(root);cout<<"\n";}

有些代码不应该被忘记,也没有源代码不应该被记住。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。