Binary Tree Postorder Traversal

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

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

Thoughts

解法很巧妙,逆序生成。类似preorder, 不过每遇到一个它是倒数的第x个。比如root是倒数第一个,然后它的最右(如果只有)是倒数第三个,最右的父节点是倒数第二个。。。

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node != null) {
                res.addFirst(node.val);
                stack.push(node.left);
                stack.push(node.right);
            }  
        }

        return res;
    }
}

Analysis

时间复杂度O(n).

Last updated