1、前序的两种实现
(1)
import java.util.ArrayList;
import java.util.List;
public class preorder {
List<Integer> list=new ArrayList<>();
public void preorder(TreeNode root){
if (root==null){
return;
}
list.add(root.val);
preorder(root.left);
preorder(root.right);
}
public List<Integer> preorderTraversel(TreeNode root){
list.clear();
preorder(root);
return list;
}
public static void main(String[] args) {
TreeNode root=BuildTree.buildTree();
preorder p=new preorder();
p.preorderTraversel(root);
}
}
(2)
import java.util.ArrayList;
import java.util.List;
public class preorder2 {
public List<Integer> preorderTraversal(TreeNode root){
if (root==null){
return new ArrayList<>();
}
List<Integer> leftPreorder=preorderTraversal(root.left);
List<Integer> rightPreorder=preorderTraversal(root.right);
List<Integer> list=new ArrayList<>();
list.add(root.val);
list.addAll(leftPreorder);
for (Integer e:rightPreorder){
list.add(e);
}
return list;
}
}
2、中序的两种实现
(1)
import java.util.ArrayList;
import java.util.List;
public class Inorder {
List<Integer> list=new ArrayList<>();
public void inorder(TreeNode root){
if (root==null){
return;
}
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
public List<Integer> inorderTraversal(TreeNode root){
list.clear();
inorder(root);
return list;
}
}
(2)
import java.util.ArrayList;
import java.util.List;
public class Inorder2 {
public List<Integer> inorderTraversal(TreeNode root){
if (root==null){
return new ArrayList<>();
}
List<Integer> list=new ArrayList<>();
List<Integer> leftInorder=inorderTraversal(root.left);
List<Integer> rightInorder=inorderTraversal(root.right);
list.addAll(leftInorder);
list.add(root.val);
for (Integer e:rightInorder){
list.add(e);
}
return list;
}
}
3、后序
import java.util.ArrayList;
import java.util.List;
public class Postorder {
List<Integer> list=new ArrayList<>();
public void postorder(TreeNode root){
if (root==null){
return;
}
postorder(root.left);
postorder(root.right);
list.add(root.val);
}
public List<Integer> postorderTraversel(TreeNode root){
list.clear();
postorder(root);
return list;
}
}