145 Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
   1
    
     2
    /
   3
return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

用的list.addFist(); 达到左右根的目的. 节点值在加的时候, 先判断是否为空. listNode 也是哦

public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> ans = new LinkedList<>();
        if (root == null) {
            return ans;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            ans.addFirst(cur.val);
            if (cur.left != null) {
                stack.push(cur.left);
            }
            if (cur.right != null) {
                stack.push(cur.right);
            }
        }
        return ans;
    }

  

原文地址:https://www.cnblogs.com/apanda009/p/7265867.html