二叉树---后序遍历(递归与迭代)

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

思路一:递归法。

代码:

 public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        postOrder(root,result);
        return result;

    }
    public void postOrder(TreeNode root,List<Integer> result){
        if(root==null)
            return;
        postOrder(root.left,result);
        postOrder(root.right,result);
        result.add(root.val);
    }

思路二:迭代法。

代码:

public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        if(root!=null){
            stack.push(root);
        }
        while(!stack.isEmpty()){
            TreeNode node=stack.peek();
            if(node!=null){
                stack.pop();// 将该节点弹出,避免重复操作,下面再将中右左节点添加到栈中
                stack.push(node);//压入中节点
                stack.push(null);//中节点只访问,未处理,压入Null来标记
                if(node.right!=null) stack.push(node.right);//压入右节点
                if(node.left!=null) stack.push(node.left);//压入左节点
            }
            else{
                stack.pop();//弹出null
                TreeNode n=stack.peek();//处理中节点
                result.add(n.val);
                stack.pop();//中节点加入结果集后弹出
            }
        }
        return result;
    }

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 14:18:02       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 14:18:02       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 14:18:02       62 阅读
  4. Python语言-面向对象

    2024-07-14 14:18:02       72 阅读

热门阅读

  1. 进制数相关

    2024-07-14 14:18:02       26 阅读
  2. 昇思25天学习打卡营第23天|LSTM+CRF序列标注

    2024-07-14 14:18:02       25 阅读
  3. QT creator简介

    2024-07-14 14:18:02       30 阅读
  4. 05.CSS 缓动变量 && 首字下沉 & 放大缩小动画

    2024-07-14 14:18:02       24 阅读
  5. iOS热门面试题(三)

    2024-07-14 14:18:02       19 阅读