一、树的遍历
🐱👓树的详细介绍
1.2 树遍历的递归用法
- 前序遍历:【头左右】;
- 中序遍历:【左头右】;
- 后序遍历:【左右头】;
1.2.1 遍历代码
/*----------------------------------------------------------------------
> File Name: treeTraverse.cpp
> Author: Jxiepc
> Mail: Jxiepc
> Created Time: Sat 05 Feb 2022 01:43:19 PM CST
----------------------------------------------------------------------*/
#include <iostream>
struct tree {
int val;
struct tree *right;
struct tree *left;
};
typedef tree treeNode;
/** 前序遍历 */
void preForeach(treeNode *head) {
if(head == nullptr)
return;
std::cout << head->val << " ";
preForeach(head->left);
preForeach(head->right);
}
/** 中序遍历 */
void midForeach(treeNode *head) {
if(head == nullptr)
return;
midForeach(head->left);
std::cout << head->val << " ";
midForeach(head->right);
}
/** 后序遍历 */
void backForeach(treeNode *head) {
if(head == nullptr)
return;
backForeach(head->left);
backForeach(head->right);
std::cout << head->val << " ";
}
void testForeach() {
treeNode n1= {1, nullptr, nullptr};
treeNode n2= {2, nullptr, nullptr};
treeNode n3= {3, nullptr, nullptr};
treeNode n4= {4, nullptr, nullptr};
treeNode n5= {5, nullptr, nullptr};
treeNode n6= {6, nullptr, nullptr};
treeNode n7= {7, nullptr, nullptr};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = &n7;
std::cout << "前序遍历:";
preForeach(&n1);
std::cout << std::endl;
std::cout << "中序遍历:";
midForeach(&n1);
std::cout << std::endl;
std::cout << "后序遍历:";
backForeach(&n1);
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
testForeach();
return 0;
}