按照箭头方向查找二叉树

花了半个小时,具体实现代码如下

package com.trs.codetool.core;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author zheng.changgang
 * @date 2019-12-18 09:44
 */
public class TreeNodeTest {

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);

        head.left.left = new Node(4);
        head.left.right = new Node(5);

        head.right.right = new Node(6);

        head.left.left.left = new Node(7);
        head.left.left.right = new Node(8);
        // 每一行打印出来
        printNode(head);

    }

    private static void printNode(Node head) {
        Queue<Node> queue = new LinkedList<>();
        List<List<Integer>> resultList = new ArrayList();
        List<Integer> rowList = new ArrayList();
        queue.offer(head);
        Node last = head;
        Node nlast = head;
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            if(cur.left != null) {
                queue.offer(cur.left);
                nlast  = cur.left;
            }
            if(cur.right != null) {
                queue.offer(cur.right);
                nlast  = cur.right;
            }

            if(cur == last) {
               // System.out.println(cur.getValue());
                last = nlast;
                rowList.add(cur.getValue());
                resultList.add(rowList);
                rowList = new ArrayList();
            }else {
                rowList.add(cur.getValue());
                //System.out.print(cur.getValue() + " ");
            }
        }
        for(int i=0;i<resultList.size();i++) {
            List<Integer> list = resultList.get(i);
            if(i % 2 == 0) {
                for(int j=0;j<list.size();j++) {
                    System.out.print(list.get(j)+" ");
                }
            } else {
                for(int j=list.size()-1;j>=0;j--) {
                    System.out.print(list.get(j)+" ");
                }
            }
            System.out.println();
        }
    }

    static class Node {
        int value;
        Node left;
        Node right;

        public Node(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        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;
        }
    }
}
posted @ 2019-12-19 09:55  未来有熊  阅读(469)  评论(0编辑  收藏  举报