树的三种遍历方式-算法

题目

树的三种遍历方式,前序,中序,后续

解题

通过递归

public static List preorderTraversal(TreeNode treeNode) {
    List result = new ArrayList<>();
    if (treeNode == null) {
      return result;
    }
    List left = preorderTraversal(treeNode.left);
    List right = preorderTraversal(treeNode.right);
    result.add(treeNode.getValue());
    result.addAll(left);
    result.addAll(right);

    return result;
  }

  public static List midorderTraversal(TreeNode treeNode) {
    List result = new ArrayList<>();
    if (treeNode == null) {
      return result;
    }
    List left = midorderTraversal(treeNode.left);
    List right = midorderTraversal(treeNode.right);
    result.addAll(left);
    result.add(treeNode.getValue());
    result.addAll(right);

    return result;
  }

  public static List backorderTraversal(TreeNode treeNode) {
    List result = new ArrayList<>();
    if (treeNode == null) {
      return result;
    }
    List left = backorderTraversal(treeNode.left);
    List right = backorderTraversal(treeNode.right);
    result.addAll(left);
    result.addAll(right);
    result.add(treeNode.getValue());

    return result;
  }

你可能感兴趣的:(算法,算法,前序遍历,后序遍历,中序遍历)