leetcode 145. Binary Tree Postorder Traversal

来源:互联网 发布:为什么需要软件测试 编辑:程序博客网 时间:2024/03/28 21:44

题目内容
Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

1
\
2
/
3

return [3,2,1].

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

题目分析
二叉树的后续遍历

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