Press "Enter" to skip to content

Binary Tree Level Order Traversal-LeetCode#102

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

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

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

思路:题目意思为给定一个二叉树按顺序返回每一层所有节点的值。递归把每个val传入List中

代码如下:

public class BinaryTreeLevelOrderTraversal {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, res, 0);
        return res;
    }

    public static void dfs(TreeNode node, List<List<Integer>> res, int deepth) {
        if (node == null) return;

        if (deepth >= res.size()) {
            res.add(new ArrayList<>());
        }

        res.get(deepth).add(node.val);

        dfs(node.left, res, deepth + 1);
        dfs(node.right, res, deepth + 1);
    }
}

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注