145.二叉树后序遍历

145.二叉树后序遍历


方法一:递归的方法


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> arraylist=new ArrayList<Integer>();

        if(root==null){
            return arraylist;
        }

        
        List<Integer> left=postorderTraversal(root.left);
        List<Integer> right=postorderTraversal(root.right);

        arraylist.addAll(left);
        arraylist.addAll(right);
        arraylist.add(root.val);

        return arraylist;
    }
}


方法二:迭代的方法


class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack=new Stack<>();
        List<Integer> list=new ArrayList<Integer>();
        TreeNode cur=root;
        TreeNode p=null; //用来记录上一个节点
        while(!stack.isEmpty()||cur!=null){
            while(cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            cur=stack.peek();
            if(cur.right==null||cur.right==p){
                list.add(cur.val);
                stack.pop();
                p=cur;
                cur=null;
            }else{
                cur=cur.right;
            }
        }
        return list;
    }
}
上一篇:二叉树的非递归遍历(递归和非递归)


下一篇:SQL SERVER 2000通过链接服务器发送邮件出现错误