The depth of the print data by the binary tree node

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/red_sheeps/article/details/80614307

Today's headlines today to interview, was asked a question about the binary tree itself is not good at arithmetic, the results like a long thought out solutions, after reminding the interviewer did he realize, came back immediately written out to achieve, see below.

Interview questions

This problem is, as a binary tree, and then printing press depth, it should be 1,2,3,4,5,6,7
Binary Tree


This is what you can expect recursion, no problem, Papa Pa achieve a pass out to achieve real results printout is: 1,2,4,5,3,6,7, it failed to achieve. Later, the interviewer said to each of the elements are stored recursively, he thought for a moment back will achieve written out, as indicated below.

Code

Node node class

Very simple, nothing to say.

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

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

The main logical approach

    private static void printNode(List<Node> nodes) {
        List<Node> listT = new ArrayList<>();
        for (Node node : nodes) {
            System.out.print(node.value + ",");
            if (node.left != null) {
                listT.add(node.left);
            }
            if (node.right != null) {
                listT.add(node.right);
            }
        }
        // 判断当前层是否有节点加入listT中,如果有,则进行递归调用
        if(!listT.isEmpty()) {
            printNode(listT);
        }
    }

To achieve the main method

    public static void main(String[] args) {
        // leaf node
        Node node4 = new Node(4, null, null);
        Node node5 = new Node(5, null, null);
        Node node6 = new Node(6, null, null);
        Node node7 = new Node(7, null, null);

        // node 2 and node 3
        Node node2 = new Node(2, node4, node5);
        Node node3 = new Node(3, node6, node7);

        // root node
        Node root = new Node(1, node2, node3);
        List<Node> list = new ArrayList<>();
        list.add(root);
        printNode(list);
    }

Execution results are as follows

Results of the

to sum up

For face questions binary tree, under normal circumstances, are inseparable from recursion, and then think about what each recursive role is, I like this question is the role of each node, because of the need to print the data by layer. If you navigate to a recursive role, think logically achieve much better.
We hope to give two faces of the opportunity ah.

Guess you like

Origin blog.csdn.net/red_sheeps/article/details/80614307