题目
树的三种遍历方式,前序,中序,后续
解题
通过递归
public static List<Integer> preorderTraversal(TreeNode treeNode) {List<Integer> result = new ArrayList<>();if (treeNode == null) {return result;}List<Integer> left = preorderTraversal(treeNode.left);List<Integer> right = preorderTraversal(treeNode.right);result.add(treeNode.getValue());result.addAll(left);result.addAll(right);return result;}public static List<Integer> midorderTraversal(TreeNode treeNode) {List<Integer> result = new ArrayList<>();if (treeNode == null) {return result;}List<Integer> left = midorderTraversal(treeNode.left);List<Integer> right = midorderTraversal(treeNode.right);result.addAll(left);result.add(treeNode.getValue());result.addAll(right);return result;}public static List<Integer> backorderTraversal(TreeNode treeNode) {List<Integer> result = new ArrayList<>();if (treeNode == null) {return result;}List<Integer> left = backorderTraversal(treeNode.left);List<Integer> right = backorderTraversal(treeNode.right);result.addAll(left);result.addAll(right);result.add(treeNode.getValue());return result;}