码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 102. Binary Tree Level Order Traversal

时间:2020-01-05 11:37:20      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:rom   link   ==   pre   style   order   oid   solution   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]
]

/**
 * 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>> arrList = new ArrayList<>();
        helper(arrList, 0, root);
        return arrList;
    }
    
    private void helper(List<List<Integer>> res, int depth, TreeNode root) {
        if (root == null) {
            return;
        }

        if (depth >= res.size()) {
            res.add(new LinkedList<>());
        }
        res.get(depth).add(root.val);
        helper(res, depth + 1, root.left);
        helper(res, depth + 1, root.right);
    }
}

[LC] 102. Binary Tree Level Order Traversal

标签:rom   link   ==   pre   style   order   oid   solution   traversal   

原文地址:https://www.cnblogs.com/xuanlu/p/12151719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!