java 力扣 102.二叉树的层序遍历

1.题目

java 力扣 102.二叉树的层序遍历_第1张图片

2.解法

①队列+BFS

class Solution {
    public List> levelOrder(TreeNode root) {
        // BFS
        List> res = new ArrayList>();
        if(root == null){
            return res;
        }
        Queue queue = new LinkedList();
        queue.offer(root);
        while(!queue.isEmpty()){
            int n = queue.size();
            List temp = new ArrayList();
            for(int i = 0; i < n; i++){
                TreeNode node = queue.poll();
                temp.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(temp);
        }
        return res;
    }
}

②数组+DFS

class Solution {
    public List> levelOrder(TreeNode root) {
        // DFS
        List> res = new ArrayList>();
        if(root == null){
            return res;
        }
        dfs(root, res, 0);
        return res;
    }
    private void dfs(TreeNode node, List> res, int level){
        if(node == null){
            return;
        }
        if(level > res.size() - 1){
            res.add(new ArrayList());
        }
        res.get(level).add(node.val);
        if(node.left != null){
            dfs(node.left, res, level + 1);
        }
        if(node.right != null){
            dfs(node.right, res, level + 1);
        }
    }
}

 

你可能感兴趣的:(力扣,二叉树,队列,dfs,leetcode,rss)