题目:给你一棵二叉树的根节点 root
,返回其节点值的 后序遍历 。
思路:左 右 根
代码:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();dfs(res, root);return res;}private void dfs(List<Integer> res, TreeNode root) {if (root == null)return;dfs(res, root.left);dfs(res, root.right);res.add(root.val);}
}
性能:
时间复杂度o(n)
空间复杂度o(n)