Leetcode 145. Binary Tree Postorder Traversal

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

For example:
Given binary tree {1,#,2,3},
return [3,2,1].

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

题意:后序遍历,即左右中。

思路:
1、分治递归遍历左右中。

public List postorderTraversal(TreeNode root) {
    List res = new ArrayList<>();
    if (root == null) {
        return res;
    }

    helper(root, res);

    return res;
}

private void helper(TreeNode node, List res) {
    if (node == null) {
        return;
    }

    helper(node.left, res);
    helper(node.right, res);
    res.add(node.val);
}

2、修改前序遍历为中右左,再把list翻转就变成了左右中。

public List postorderTraversal1(TreeNode root) {
    List res = new ArrayList<>();
    if (root == null) {
        return res;
    }

    Stack stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode cur = stack.pop();
        res.add(cur.val);
        if (cur.left != null) {
            stack.push(cur.left);
        }
        if (cur.right != null) {
            stack.push(cur.right);
        }
    }

    Collections.reverse(res);

    return res;
}

你可能感兴趣的:(Leetcode 145. Binary Tree Postorder Traversal)