树的几种遍历方法介绍
创始人
2024-06-03 11:47:54

本文主要介绍数据结构“树(tree)”的几种常见的遍历方式,同时给出相应的示例代码。

1 概述

与线性数据结构(如数组、链表、队列、栈)只有一种遍历逻辑方法不同,树可以通过不同的方法进行遍历。

常见的树的遍历方法包括:中序遍历(InOrder Traversal)、前序遍历(PreOrder Traversal)及后序遍历(PostOrder Traversal)。

下图给出了这几种遍历方法访问到节点的顺序:

2 前序遍历(PreOrder Traversal)

2.1 算法

前序遍历的算法实现为:

1. Visit the root;
2. Traverse the left subtree, i.e., call Preorder(left->subtree);
3. Traverse the right subtree, i.e., call Preorder(right->subtree) .

2.2 使用场景

前序遍历可用于创建树的拷贝,同时也可用于获取表达树的前缀表达式。

2.3 示例代码

下面通过一道leetcode题来演示前序遍历的代码。

题目信息:

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples).

Example:

Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]

解法:

此题可通过递归法以“Depth-First Search”方式解决,相关代码如下:

/*
// Definition for a Node.
class Node {
public:int val;vector children;Node() {}Node(int _val) {val = _val;}Node(int _val, vector _children) {val = _val;children = _children;}
};
*/class Solution {
public:vector preorder(Node* root) {vector result;traverse(root, result);return result;}private:// traverse tree elements recursivelyvoid traverse(Node* root, vector& result) {// if root is emptyif (nullptr == root) {return;}// store the root of the tree firstresult.push_back(root->val);// store the children of the treefor (auto node:(root->children)) {traverse(node, result);}return;}
};

相关内容

热门资讯

在深化两岸融合发展中走亲走近、... 转自:贵州日报 夏日福建,第十八届海峡论坛如约而至。台湾有关政党代表以及工会、青年、妇女、民间信仰、...
湄潭茶企开足马力 转自:贵州日报 6月11日,遵义市湄潭县越崎茶业有限公司生产车间内,各条制茶生产线高速运转。作为当地...
花式迎端午 12日至13日,“2026澎湃洞江湖”龙舟邀请赛在福州新区(长乐区)洞江湖公园开赛。本次赛事以舟为媒...
优胜者有机会破格晋升高级工 转自:贵州日报 本报讯(记者 杨唯)贵阳贵安2026年职业技能大赛暨贵阳市第五届“筑城工匠杯”职工职...
重庆公积金 小程序月底关停 办... 6月12日,重庆市住房公积金管理中心发布消息,“重庆公积金”小程序将于6月30日18时关停,缴存人可...