Skip to content

Latest commit

 

History

History
executable file
·
71 lines (64 loc) · 1.37 KB

145. Binary Tree Postorder Traversal.md

File metadata and controls

executable file
·
71 lines (64 loc) · 1.37 KB

145. Binary Tree Postorder Traversal

Question

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Thinking:

  • Method : 递归
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        post(root, result);
        return result;
    }
    private void post(TreeNode root, List<Integer> result){
        if(root == null) return;
        post(root.left, result);
        post(root.right, result);
        result.add(root.val);
    }
}

二刷

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        post(root, result);
        return result;
    }
    private void post(TreeNode node, List<Integer> result){
        if(node == null) return;
        post(node.left, result);
        post(node.right, result);
        result.add(node.val);
    }
}