145. Binary Tree Postorder Traversal

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了145. Binary Tree Postorder Traversal相关的知识,希望对你有一定的参考价值。

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

Example:

Input: [1,null,2,3]
   1
         2
    /
   3

Output: [3,2,1]
class Solution 
    public List<Integer> postorderTraversal(TreeNode root) 
        if (root == null) return new LinkedList();
        Stack<TreeNode> s = new Stack<TreeNode>();
        LinkedList<Integer> res = new LinkedList();
        s.push(root);
        while(!s.empty())
            TreeNode p = s.pop();
            res.addFirst(p.val);
            //左右根,push进stack是第一次逆,addFirst又逆回来,所以还是左右根
            if(p.left != null)
                s.push(p.left);
            
            if(p.right != null)
                s.push(p.right);
            
        
        return res;
    

LinkedList有addFirst方法,巧妙。

以上是关于145. Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章