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},

   1
    \
     2
    /
   3

return [3,2,1].


Analysis:

postorder: left subtree - right subtree - root


Java code

20160602

recursion

/**
 * 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) {
        //postorder: left subtree - right subtree - root
        List<Integer> result = new ArrayList<Integer>();
        postorderTraversal(root, result);
        return result;
    }
    
    private void postorderTraversal(TreeNode root, List<Integer> list) {
        if(root == null) {
            return;
        }
        postorderTraversal(root.left, list);
        postorderTraversal(root.right, list);
        list.add(root.val);
    }
}

 

posted @ 2016-06-03 10:22  茜茜的技术空间  阅读(153)  评论(0编辑  收藏  举报