Location>code7788 >text

Hierarchical traversal (breadth-first search) -102

Popularity:521 ℃/2024-08-29 22:08:41

Title Description

Given the root node of a binary tree, return a hierarchical traversal of its node values. (i.e., layer by layer, visiting all nodes from left to right).

Ideas for solving the problem

Here we hierarchical traversal we need to use the data structure of the queue, we traverse in turn from the root node, we need to use a variable to record the number of elements in our queue at this time, because this way we know that we need to know this level of how many elements from the queue to pop out of the elements we add to the collection, and then pop out the elements of the left and right child nodes in turn to add the queue to us! Of course, here we have to determine the end of the traversal conditions - that is, when all the elements in our layer have no left and right child nodes, we end our traversal!

code example

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();

        if (root == null) {
            return result;
        }
        // TreeNode index=root;
        Queue<TreeNode> queue = new LinkedList<>();
        //Used to determine the conditions for traversal termination
        int judge = 1;
        (root);
        while (judge != 0) {
            int size = ();
            //Used to determine the conditions for traversal termination
            int xiao = 0;
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i <= size; i++) {
                TreeNode temp = ();
                ();
                if ( != null) {
                    ();
                    xiao = 1;
                }
                if ( != null) {
                    ();
                    xiao = 1;
                }

            }
            (list);
            if (xiao == 1) {
                judge = 1;
            } else {
                judge = 0;
            }
        }
        return result;
    }
}