二叉樹遍歷 前序 中序 後序


package com.pay.test; import java.util.LinkedList; public class Node { private Integer data; private Node left; private Node right; public Integer getData() { return data; } public void setData(Integer data) { this.data = data; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public Node(Integer data) { this.data = data; } public static Node createNode(LinkedList<Integer> list){ if(list==null || list.isEmpty()){ return null; } Integer data= list.removeFirst(); Node node; if(data!=null ){ node=new Node(data); } return null; } //前序遍歷 public void preOrderPrint(Node root){ if(root==null){ return; }else { System.out.println(root.data+""); preOrderPrint(root.left); preOrderPrint(root.right); } } //中序遍歷 public void inOrderPrint(Node node){ if(node==null){ return; }else { inOrderPrint(node.left); System.out.println(node.data); inOrderPrint(node.right); } } //後續遍歷 public void postOrderPrint(Node node){ if(node==null){ return; }else { postOrderPrint(node.left); postOrderPrint(node.right); System.out.println(node.data); } } }

  測試類

package com.pay.test;

public class Test {

    public static void main(String[] args) {

    Node root=new Node(1);
        Node left=new Node(22);
        Node left1=new Node(44);
        Node left2=new Node(44);

        Node right=new Node(55);
        Node right1=new Node(6);
        Node right2=new Node(7);
        left1.setLeft(left2);
        left.setLeft(left1);
        root.setLeft(left);

        right1.setRight(right2);
        right.setRight(right1);
        root.setRight(right);

        System.out.println("前序遍歷");
        root.preOrderPrint(root);

        System.out.println("中序遍歷");
        root.inOrderPrint(root);

        System.out.println("後序遍歷");
        root.postOrderPrint(root);


    }
}

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章