构建一个二叉树,打印出这个二叉树的同层数

 

public class Node {

    private int id;
    private Node right;
    private Node left;
    
    public Node(int id, Node right, Node left) {
        super();
        this.id = id;
        this.right = right;
        this.left = left;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Node getRight() {
        return right;
    }
    public void setRight(Node right) {
        this.right = right;
    }
    public Node getLeft() {
        return left;
    }
    public void setLeft(Node left) {
        this.left = left;
    }
    
}

 

这个输出list 是逆序的,

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Lianxi {

    private int temp=0;
    static Map<Integer, List<Integer>> map =new HashMap<>();
    public static void main(String[] args) {
        Node node=new Node(1, new Node(1, new Node(3, null, null),new Node(5, null, null) ), new Node(4, new Node(4, null, new Node(6, null, null)), new Node(6, null, null)));
        method02(node, 0);
        System.out.println(map);
    }
    //这里是取node子节点的值
    public static List method01 (Node node){
        List<Integer> list =new ArrayList<>();
        if (node.getLeft()!=null) {
            list.add(node.getLeft().getId());
        }
        if (node.getRight()!=null) {
            list.add(node.getRight().getId());
        }
        return list;
    }
    
    public static void method02(Node root,int temp){
        ++temp;
        if(method01(root)!=null&&map.get(temp)!=null){
            List<Integer> list=map.get(temp);
            
            for(int i=0;i<method01(root).size();i++){
                list.add((Integer)(method01(root)).get(i));
            }
            map.put(temp, list);
            if (root.getLeft()!=null) {
                method02(root.getLeft(), temp);
            } 
            if (root.getRight()!=null) {
                method02(root.getRight(), temp);
            }
        }else if(method01(root)!=null&&map.get(temp)==null){
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<method01(root).size();i++){
                list.add((Integer)(method01(root)).get(i));
            }
            map.put(temp, list);
            if (root.getLeft()!=null) {
                method02(root.getLeft(), temp);
            } 
            if (root.getRight()!=null) {
                method02(root.getRight(), temp);
            }
            
        }
    }
    
}

 

 

输出的是一个map

 

posted on 2018-03-30 18:27  期待华丽转身  阅读(183)  评论(0编辑  收藏  举报