二叉树的中序遍历

考察二叉树的遍历是考察一个人数据结构能力最基本的方法。我们熟知的二叉树的遍历有前序遍历、中序遍历和后序遍历。所谓的二叉树的遍历顺序的不同也只是对于根节点的访问时机的不同。所有我们只要掌握了其中一种二叉树的遍历顺序的算法也就基本上掌握了二叉树的遍历算法,故我们以二叉树的中序遍历为例做探究。

方法1:递归

当我们接收到一颗二叉树的根节点时,开始递归访问该二叉树的左子树(将二叉树的左孩子结点传进去),直到遇到空节点做为递归函数的出口。然后输出根节点(或者将根节点插入一个vector容器中),然后进行右子树遍历,同样遇到空间点即遇到叶子节点时退出递归进行回溯。

Leecode算法(将根节点插入容器):

class Solution {
public:
    void inorder(TreeNode *root,vector<int>&res){
        if(!root) return;
        inorder(root->left,res);
        res.push_back(root->val);
        inorder(root->right,res);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        inorder(root,res);
        return res;
    }
};

本地运行程序(将根节点进行输出):

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct BinaryNode
{
//数据域
char ch;
//指针域
struct BinaryNode* lChild;//左孩子
struct BinaryNode* rChild;//右孩子
};
//进行递归遍历二叉树的实现
void recuraion(struct BinaryNode* root)
{
//如果root为空时终止递归调用
if (root == NULL)
{
return;
}
//中序遍历


//先左
recuraion(root->lChild);
//输出根
printf("%c ", root->ch);
//再右
recuraion(root->rChild);
}
void test01()
{
struct BinaryNode nodeA={'A',NULL,NULL};
struct BinaryNode nodeB={'B',NULL,NULL};
struct BinaryNode nodeC={'C',NULL,NULL};
struct BinaryNode nodeD={'D',NULL,NULL};
struct BinaryNode nodeE={'E',NULL,NULL};
struct BinaryNode nodeF={'F',NULL,NULL};
struct BinaryNode nodeG={'G',NULL,NULL};
struct BinaryNode nodeH={'H',NULL,NULL};
//建立关系
nodeA.lChild = &nodeB;
nodeA.rChild = &nodeF;
nodeB.rChild = &nodeC;
nodeF.rChild = &nodeG;
nodeC.lChild = &nodeD;
nodeC.rChild = &nodeE;
nodeG.lChild = &nodeH;
//递归遍历操作
recuraion(&nodeA);
}
int main()
{
test01();
system("pause");
return 0;
}

方法2:非递归

我们可以考虑使用LeetCode上的算法思路进行非递归的二叉树遍历。首先我们维护一个栈来将二叉树的根节点以及它的所有左孩子结点进行入栈,当左孩子为空时即停止入栈将栈中元素进行弹出,并将弹出元素插入进行维护的一个vector容器中,然后进行访问该根节点的右孩子,步骤同上。最后栈为空时,二叉树的中序遍历也就完成了。

算法演示:

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/er-cha-shu-de-zhong-xu-bian-li-by-leetcode-solutio/
来源:力扣(LeetCode)

 

posted @ 2021-05-06 23:52  花瓣飘落的地方  阅读(630)  评论(0编辑  收藏  举报