leetcode-102 二叉树的层序遍历 Java

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/tao-mo-ban-bfs-he-dfs-du-ke-yi-jie-jue-by-fuxuemin/

方法一:DFS

/**
 * 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) {
        List<List<Integer>> res = new ArrayList<>();
        if (root != null) {
            dfs(res, root, 0);
        }
        return res;
    }

    private void dfs (List<List<Integer>> res, TreeNode node, int level) {
        if (res.size() - 1 < level) {
            res.add(new ArrayList<Integer>());
        }
        res.get(level).add(node.val);
        if (node.left != null) {
            dfs(res, node.left, level + 1);
        }
        if (node.right != null) {
            dfs(res, node.right, level + 1);
        }
    }  
}

方法二: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) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            int curSize = q.size();
            LinkedList<Integer> subList = new LinkedList<>();
            for (int i = 0; i < curSize; i++) {
                TreeNode curr = q.poll();
                if (curr != null) {
                    subList.add(curr.val);
                    if (curr.left != null) {
                        q.offer(curr.left);
                    }
                    if (curr.right != null) {
                        q.offer(curr.right);
                    }
                }
            }
            res.add(subList);
        }
        return res;
    }
}```

你可能感兴趣的:(dfs,java,leetcode,bfs)