【LeetCode从零单排】No102 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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

基本二叉树这块用的都是递归,现在还是有点蒙。

代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> al=new ArrayList<List<Integer>>();
        levelHelper(al,root,0);
        return al;
        
    }
    public void levelHelper(List<List<Integer>> res,TreeNode root,int height){
        if(root==null) return;
        if(height>=res.size()){
            res.add(new ArrayList<Integer>());
            
    }
        res.get(height).add(root.val);
        levelHelper(res,root.left,height+1);
        levelHelper(res,root.right,height+1);

 }
}    

代码下载:https://github.com/jimenbian/GarvinLeetCode


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



你可能感兴趣的:(java,LeetCode)