145. Binary Tree Postorder Traversal
by Botao Xiao
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 : 递归 ```Java /**
- Definition for a binary tree node.
- public class TreeNode {
- int val;
- TreeNode left;
- TreeNode right;
- TreeNode(int x) { val = x; }
- }
*/
class Solution {
public List
postorderTraversal(TreeNode root) { List result = new ArrayList<>(); post(root, result); return result; } private void post(TreeNode root, List 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);
}
}
Subscribe via RSS