zoukankan      html  css  js  c++  java
  • 【LeetCode】145. 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实现

  • 相关阅读:
    ios初级必看视频
    Md5加密
    Jmail发送邮件
    NPOI Helper文档
    jquery 序列化
    mvc DropDownList默认选项
    获取HTML
    EntityFramework Reverse POCO Generator工具
    全选反选
    mvc导出EXCEL
  • 原文地址:https://www.cnblogs.com/yongh/p/11791319.html
Copyright © 2011-2022 走看看