力扣简145 二叉树的后序遍历++--

树 后序遍历 递归调用  迭代(没写)

 

复制代码
package leetcode01;
import java.util.*;

public class Solution145 {
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new LinkedList<Integer>();
        res=postorder(root, res);
        return res;
    }
    
    public static List<Integer> postorder(TreeNode root,List<Integer> res) {
        if(root!=null) {//这里最开始写的while,导致在递归第一个root.left不断的把left的val值add进去,应该是if。
            if(root.left!=null) {
                postorder(root.left,res);
            }
            if(root.right!=null) {
                postorder(root.right,res);
            }
            res.add(root.val);
        }
        return res;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeNode p=new TreeNode(12,new TreeNode(),new TreeNode(-60,null,null));
        System.out.print(postorderTraversal(p));
    }

}
复制代码

 这个迭代是抄的!

复制代码
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new LinkedList<Integer>();
        if(root==null) {
            return res;
        }
        Deque<TreeNode> stack=new LinkedList<TreeNode>();
        TreeNode pre=null;  //粗略看了题解,写的时候把这里设置成root,这样有的情况会出错,应该是null。
        while(root!=null||!stack.isEmpty()) {
            while(root!=null) {
                stack.push(root);//add=addLast push=addfirst
                root=root.left;
            }
            root=stack.poll(); //poll=pop
            if(root.right==null || root.right==pre) {//后一种情况表示刚处理完右节点
                res.add(root.val);
                pre=root;
                root=null;
            }
            else {
                stack.push(root);
                root=root.right;
            }
        }
        return res;
    }
复制代码

 

posted @   Ssshiny  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示