力扣简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; }

浙公网安备 33010602011771号