Leetcode145——Binary Tree Postorder Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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].

2. 求解

这个题就是一个树的后序遍历问题,最简单的方案就是递归的遍历子树,要注意递归退出的条件。

/**
 * 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) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null) {
            return list;
        }
        List<Integer> left = postorderTraversal(root.left);
        List<Integer> right = postorderTraversal(root.right);
        list.addAll(left);
        list.addAll(right);
        list.add(root.val);
        return list;
    }
}
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/0df651cd248e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞