LeetCode145. Binary Tree Postorder Traversal

Posted 华仔要长胖

tags:

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

Difficulty: Hard

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/binary-tree-postorder-traversal/

Given a binary tree, return the postordertraversal of its nodes\' values.

Example:

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

Output: [3,2,1]

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

Intuition

Method 1. Using one stack to store nodes, and another to store a flag wheather the node has traverse right subtree.

Method 2. Stack + Collections.reverse( list )

 

Solution

Method 1

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<Integer>();
        Stack<TreeNode> nodeStk = new Stack<TreeNode>();
        Stack<Boolean> tag = new Stack<Boolean>();
        while(root!=null || !nodeStk.isEmpty()){
            while(root!=null){
                nodeStk.push(root);
                tag.push(false);
                root=root.left;
            }
            if(!tag.peek()){
                tag.pop();
                tag.push(true);
                root=nodeStk.peek().right;
            }else{
                list.add(nodeStk.pop().val);
                tag.pop();
            }
        }
        return list;
    }

  

Method 2

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        Stack<TreeNode> stk = new Stack<>();
        stk.push(root);
        while(!stk.isEmpty()){
            TreeNode node = stk.pop();
            if(node==null)
                continue;
            list.addFirst(node.val);  //LinkedList\'s method. If using ArrayList here,then using \'Collections.reverse(list)\' in the end;
            stk.push(node.left);
            stk.push(node.right);
        }
        return list;
    }

  

Complexity

Time complexity : O(n)

Space complexity : O(nlogn)

 

What I\'ve learned

1. linkedList.addFirst( e )

2. Collections.reverse( arraylist )

 

 More:【目录】LeetCode Java实现

 

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

leetcode 145. Binary Tree Postorder Traversal

LeetCode 145:Binary Tree Postorder Traversal

leetcode145. Binary Tree Postorder Traversal

LeetCode 145: Binary Tree Postorder Traversal

leetcode No145. Binary Tree Postorder Traversal

LeetCode OJ 145. Binary Tree Postorder Traversal