一个普通二叉树的遍历
2023-09-27 14:28:09 时间
要点:二叉树遍历,要针对基本图形的遍历,先序(NLR),中序(LNR),后序(LRN),且往上看,它是某节点的左子,但往下看,它可能还是某节点的根,这时就要继续往下找,直到找到没有子(也就是叶子)时,左子,才是真正的左子,自己体会。
图形:
程序:
#include<stdio.h> #include<stdlib.h> struct node{ char data; struct node* left; struct node* right; }; struct node* newNode(char data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data=data; node->left=NULL; node->right=NULL; return node; } void printPostorder(struct node* node){ if(node == NULL) return; printPostorder(node->left); printPostorder(node->right); printf("%c ",node->data); } void printInorder(struct node* node){ if(node==NULL){ return; } printInorder(node->left); printf("%c ",node->data); printInorder(node->right); } void printPreorder(struct node* node){ if(node==NULL){ return; } printf("%c ",node->data); printPreorder(node->left); printPreorder(node->right); } int main(){ struct node *root=newNode('A'); root->left=newNode('B'); root->right=newNode('C'); root->left->left=newNode('D'); root->right->left=newNode('F'); root->right->right=newNode('H'); root->left->left->right=newNode('E'); root->right->right->left=newNode('I'); root->right->right->right=newNode('G'); printf("\nPreorder raversal of binary tree is \n"); printPreorder(root); printf("\nInorder raversal of binary tree is \n"); printInorder(root); printf("\nPostorder raversal of binary tree is \n"); printPostorder(root); return 0; }
输出:
Preorder raversal of binary tree is A B D E C F H I G Inorder raversal of binary tree is D E B A F C I H G Postorder raversal of binary tree is E D B F G I H C A
相关文章
- Java实现二叉树的创建、递归/非递归遍历
- LeetCode高频题:二叉树的锯齿形(Z字形,之字形)层序遍历
- 让整棵二叉树都被相机覆盖到,请问要给二叉树放多少台相机?
- 五二不休息,今天也学习,从JS执行栈角度图解递归以及二叉树的前、中、后遍历的底层差异
- 剑指offer解法汇总84-二叉树中和为某一值的路径(三)
- 力扣解法汇总998-最大二叉树 II
- 力扣解法汇总919-完全二叉树插入器
- 二叉树遍历(前序、中序、后序)stack
- LeetCode199之二叉树的右视图(二叉树的深度遍历和广度遍历)
- 113、【树与二叉树】leetcode ——538. 把二叉搜索树转换为累加树:递增数组视角右中左遍历(C++版本)
- 43、【树和二叉树】二叉树的先、中、后和层次遍历方法合集(C/C++版)
- Go语言二叉树定义及遍历算法实现
- 求二叉树的先序遍历
- 51. 腾讯面试题:一个二叉树,中序遍历,找一个节点的后一个节点
- 【Leetcode】101:对称二叉树(Python)
- [CareerCup] 4.7 Lowest Common Ancestor of a Binary Search Tree 二叉树的最小共同父节点
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
- LeetCode二叉树相同树比较
- 【bzoj1864】[ZJOI2006]三色二叉树 树形dp
- leetcode 110. Balanced Binary Tree 平衡二叉树(简单)