java 多叉树遍历 后序 左-右-根

实体类:

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);
  }

结果:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值