任务是打印给定二叉树的左节点。首先,用户将插入数据,从而生成二叉树,然后打印所形成的树的左视图。
每个节点最多可以有 2 个子节点,因此这里程序必须仅遍历与节点关联的左指针
如果左指针不为空,则意味着它将有一些与之关联的数据或指针,否则它将是要打印并显示为输出的左子级。
示例
Input : 1 0 3 2 4Output : 1 0 2
登录后复制
这里,橙色节点代表二叉树的左视图。
在给定的图中,数据为 1 的节点是根节点,因此它将被打印,而不是转到左子节点,它将打印 0,然后它将转到 3 并打印其左子节点,即 2。
立即学习“C语言免费学习笔记(深入)”;
我们可以使用递归方法来存储节点的级别并重复转移到
下面的代码显示了给定算法的 C 实现
算法
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *left, *right Step 2 -> create function for inserting node with parameter as new_data Declare temp variable of node using malloc Set temp->data = new_data Set temp->left = temp->right = NULL return temp Step 3 -> declare function void left_view(struct node* root, int level, int* highest_level) IF root = NULL Exit End IF *highest_level data Set *highest_level = level End Recursively call left_view(root->left, level + 1, highest_level) Recursively call left_view(root->right, level + 1, highest_level) Step 4 -> Declare Function void left(struct node* root) Set int highest_level = 0 Call left_view(root, 1, &highest_level) Step 5-> In main() Call New passing value user want to insert as struct node* root = New(1) Call left(root)STOP
登录后复制
示例
#include #include //create a structure of a nodestruct node { int data; struct node *left, *right; //this pointer will point to the nodes attached with a node};struct node* New(int new_data) { struct node* temp = (struct node*)malloc(sizeof(struct node)); //allocating memory to a pointer dynamically temp->data = new_data; temp->left = temp->right = NULL; return temp;}void left_view(struct node* root, int level, int* highest_level) { if (root == NULL) //if there is no node that means no data return; // this function will retrun the root node if there is only root node in a tree if (*highest_level data); *highest_level = level; } // Recursive function left_view(root->left, level + 1, highest_level); left_view(root->right, level + 1, highest_level);}void left(struct node* root) { int highest_level = 0; left_view(root, 1, &highest_level);}int main() { printf("left view of a binary tree is : "); struct node* root = New(1); root->left = New(0); root->right = New(3); root->right->left = New(2); root->right->right = New(4); left(root); return 0;}
登录后复制
输出
如果我们运行上面的程序,它将生成以下输出。
left view of a binary tree is : 1 0 2
登录后复制
以上就是在C语言中打印二叉树的左视图的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2584044.html