【408DS算法题】026基础-二叉树的先序、中序、后序遍历

Index

    • 题目
    • 分析实现
    • 总结

题目

给定二叉树的根节点root,分别写出递归函数实现对二叉树的先序遍历、中序遍历和后序遍历。


分析实现

二叉树的先序、中序、后序遍历是非常常见的对二叉树进行深度优先搜索的算法。三种算法的思想类似,对于每一步的搜索,都是将结点分为 curcur->leftcur->right 这样的三部分按不同的顺序进行访问(其“先” “中” “后” 的称呼就来自于cur的访问地位)。具体顺序如下:

  • 先序遍历:1.cur; 2.cur->left; 3.cur->right.
  • 中序遍历:1.cur->left; 2.cur; 3.cur->right.
  • 后序遍历:1.cur->left; 2.cur->right; 3.cur.

具体实现如下:

// 二叉树节点定义
struct BTNode {
	int val;
	BTNode *left;
	BTNode *right;
};

// 先序遍历
void preOrder(BTNode *root) {
	if (root == nullptr) 
		return;
		
	visit(root);	// 访问结点cur,这里写完函数的形式,也可以是 cout<val<<" ";
	preOrder(root->left);
	preOrder(root->right);
}

// 中序遍历
void inOrder(BTNode *root) {
	if (root == nullptr)
		return;
		
	inOrder(root->left);
	visit(root);
	inOrder(root->right);
}

// 后序遍历
void postOrder(BTNode *root) {
	if (root == nullptr)
		return;
		
	postOrder(root->left);
	postOrder(root->right);
	visit(root);
}

总结

以上就是二叉树常见的三种DFS——先序、中序、后序遍历的实现。

代码采用了递归写法,十分通俗易懂,但具体使用时要熟练掌握,以方便应对各种小变化。

你可能感兴趣的:(算法,链表,数据结构)