Leetcode (Java) -102. Binary tree hierarchy traversal

Given a binary tree, the node returns its value hierarchical traversal. (Ie, layer by layer, from left to right to access all nodes).

For example:
Given a binary tree: [3,9,20, null, null, 15,7],

    3
   / \
  920
    / \
   157
to return to its level through the results:

[
  [3],
  [9,20],
  [15,7]
]

 

Ideas: BFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null) return new ArrayList<>();

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<List<Integer>> list=new ArrayList<>();
        while(!queue.isEmpty())
        {
            int levelSize=queue.size();
            List<Integer> levelNodes = new ArrayList<>();
            for(int i=0;i<levelSize;i++){
                TreeNode current=queue.pollFirst();
                if(current.left!=null)
                    queue.add(current.left);
                if(current.right!=null)
                    queue.add(current.right);
                levelNodes.add(current.val);
            }
            list.add(levelNodes);
        }
        return list;
    }
}

 

Published 142 original articles · won praise 31 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/104070988