题目来源:https://leetcode.com/problems/binary-tree-postorder-traversal/
问题描述
145. Binary Tree Postorder Traversal
Hard
Given a binary tree, return the postordertraversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
------------------------------------------------------------
题意
二叉树的后序遍历
------------------------------------------------------------
思路
递归
------------------------------------------------------------
代码
/**
* 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> ans = new ArrayList<Integer>();
dfs(root, ans);
return ans;
}
private void dfs(TreeNode root, List<Integer> ans) {
if (root == null) {
return;
}
dfs(root.left, ans);
dfs(root.right, ans);
ans.add(root.val);
}
}