码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】145. Binary Tree Postorder Traversal

时间:2019-11-04 13:56:04      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:html   ref   using   HERE   out   base   pos   lis   pop   

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实现

 

【LeetCode】145. Binary Tree Postorder Traversal

标签:html   ref   using   HERE   out   base   pos   lis   pop   

原文地址:https://www.cnblogs.com/yongh/p/11791319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!