Accepted tiny java code by reversing (root, right, left)


  • 5
    R

    the idea is to convert the problem to (root, right, left) with add first into the linkedlist.

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

  • 0
    L

    Very smart usage of linked list.


  • 0
    W

    Nice solution.Easy to understand .


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.