二叉树的递归遍历

二叉树的递归遍历

题目链接:

144.二叉树的前序遍历(简单)

94.二叉树的中序遍历(简单)

145.二叉树的后序遍历(简单)

题解:

思路:弄清递归三要素

  1. 确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。

  2. 确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。

  3. 确定单层递归的逻辑: 确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。

代码(C++):

//二叉树的节点
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    //构造函数
    TreeNode(int value) : val(value), left(nullptr), right(nullptr) {}
};
​
//二叉树的前序遍历
class Solution1 {
public:
    void preorder (TreeNode *root, vector<int> &result) {
        if (root == nullptr) return;
        result.push_back(root->val);
        preorder(root->left, result);
        preorder(root->right, result);
    }
​
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> result;
        preorder(root, result);
        return result;
    }
};
​
//二叉树的中序遍历
class Solution2 {
public:
    void inorder(TreeNode *root, vector<int> &result) {
        if (root == nullptr) return;
        inorder(root->left, result);
        result.push_back(root->val);
        inorder(root->right, result);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        inorder(root, result);
        return result;
    }
};
​
//二叉树的后续遍历
class Solution3 {
public:
    void postorder(TreeNode* root, vector<int>& result) {
        if (root == nullptr) return;
        postorder(root->left, result);
        postorder(root->right, result);
        result.push_back(root->val);
    }
​
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        postorder(root, result);
        return result;
    }
};

分析:

  • 时间复杂度:O(N),N表示二叉树中结点的个数;

  • 空间复杂度:执行递归遍历算法时,系统都会用到一个栈,栈的最大深度等于二叉树的深度加一,而二叉树的深度视具体形态决定,若二叉树为理想平衡树或接近理想平衡树,则二叉树的深度大致为 lbn,所以空间复杂度为 O(lbn),若二叉树退化为一棵单支树(最坏的情况),则空间复杂度为 O(N)。

posted @ 2021-11-25 10:04  wltree  阅读(143)  评论(0编辑  收藏  举报