关闭

leetcode 145. Binary Tree Postorder Traversal

标签: leetcode
111人阅读 评论(0) 收藏 举报
分类:

题目内容
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23454次
    • 积分:930
    • 等级:
    • 排名:千里之外
    • 原创:70篇
    • 转载:17篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论