实体类:
public class TreeNode {
@Getter @Setter
public Integer val;
@Getter @Setter
public List<TreeNode> children;
@Getter @Setter
private int index=0;
public TreeNode(){}
public TreeNode(int val){this.val=val;}
public TreeNode(int val, List<TreeNode> children){
this.val=val;
this.children=children;
}
}
遍历方法:
private void preorder2(TreeNode root){
if(root!=null){
Stack<TreeNode> stack=new Stack<>();
while (!stack.isEmpty()||root!=null){
while (root!=null){
stack.push(root);
if(root.children==null){
root=null;
}else{
root=root.children.get(root.getIndex());
}
}
root=stack.pop();
if(root.children==null|| root.getIndex()>=root.children.size()){
System.out.println(root.val);
root=null;
if(stack.size()>0){
stack.peek().setIndex(stack.peek().getIndex()+1);
}
}else {
stack.push(root);
root=root.children.get(root.getIndex());
}
}
}
}
调用:
private void test(){
TreeNode node1=new TreeNode(1,new ArrayList<>());
TreeNode node2=new TreeNode(2,new ArrayList<>());
TreeNode node3=new TreeNode(3,null);
TreeNode node4=new TreeNode(4,new ArrayList<>());
TreeNode node5=new TreeNode(5,new ArrayList<>());
TreeNode node6=new TreeNode(6,null);
TreeNode node7=new TreeNode(7,null);
TreeNode node8=new TreeNode(8,new ArrayList<>());
TreeNode node9=new TreeNode(9,null);
TreeNode node10=new TreeNode(10,null);
TreeNode node11=new TreeNode(11,null);
TreeNode node12=new TreeNode(12,null);
TreeNode node13=new TreeNode(13,null);
node1.getChildren().add(node2);
node1.getChildren().add(node3);
node2.getChildren().add(node4);
node2.getChildren().add(node5);
node2.getChildren().add(node8);
node4.getChildren().add(node13);
node5.getChildren().add(node9);
node5.getChildren().add(node6);
node5.getChildren().add(node7);
node8.getChildren().add(node10);
node8.getChildren().add(node11);
node8.getChildren().add(node12);
System.out.println("-------后序遍历-迭代(模拟递归)------");
preorder2(node1);
}
结果: