DFS&Iteration Binary Tree Postorder Traversal

本文详细介绍了二叉树后序遍历的三种实现方法:递归(DFS)、迭代,包括代码实现及时间、空间复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
二叉树的后序遍历。

方法一:DFS。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    void dfs(vector<int> &ans, TreeNode* node) {
        if(node == nullptr) return;
        if(node->left != nullptr) {
            dfs(ans, node->left);
        }
        if(node->right != nullptr) {
            dfs(ans, node->right);
        }
        ans.push_back(node->val);
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        dfs(ans, root);
        return ans;
    }
};

方法二:迭代。
时间复杂度O(N),空间复杂度O(N)。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        TreeNode *p, *q;
        stack<TreeNode*> s;
        p = root;
        do {
            while(p != nullptr) {
                s.push(p);
                p = p->left;
            }
            q = nullptr;
            while(!s.empty()) {
                p = s.top();
                s.pop();
                if(p->right == q) {
                    ans.push_back(p->val);
                    q = p;
                }else {
                    s.push(p);
                    p = p->right;
                    break;
                }
            }
        }while(!s.empty());
        return ans;
    }
};

方法三:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值