【力扣每日一题】力扣145二叉树的后序遍历

题目来源

力扣145二叉树的后序遍历

题目概述

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

思路分析

使用迭代和递归方法都可以实现二叉树的后序遍历。

代码实现

java实现

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode last = null;
        while (root!= null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == last) {
                res.add(root.val);
                last = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
}

c++实现

class Solution {
public:
    vector<int> res;
    vector<int> postorderTraversal(TreeNode* root) {
        if (root == nullptr) {
            return res;
        }
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        res.push_back(root->val);
        return res;
    }
}

最近更新

  1. TCP协议是安全的吗?

    2024-02-13 15:48:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-13 15:48:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-13 15:48:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-13 15:48:02       18 阅读

热门阅读

  1. linux 发送自定义包裹 c 程序

    2024-02-13 15:48:02       34 阅读
  2. [Ubuntu] Disabled IPv6

    2024-02-13 15:48:02       35 阅读
  3. C++自动变量和static声明静态局部变量

    2024-02-13 15:48:02       27 阅读
  4. 某黑马magnet搜索接口

    2024-02-13 15:48:02       29 阅读
  5. 【Lazy ORM】select One查询

    2024-02-13 15:48:02       36 阅读
  6. SpringCloud入门概述

    2024-02-13 15:48:02       26 阅读
  7. 类与结构体(5)

    2024-02-13 15:48:02       29 阅读